mirror of
https://github.com/permissionlesstech/bitchat.git
synced 2026-07-27 04:25:20 +00:00
Compare commits
18
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5e69a19cb3 | ||
|
|
5c2903ec7c | ||
|
|
cbfdb9696e | ||
|
|
87cbf5a03c | ||
|
|
d2a47d1ade | ||
|
|
0bde6d21f7 | ||
|
|
f718097c74 | ||
|
|
0152196ac2 | ||
|
|
14e7b428d9 | ||
|
|
c671e3df66 | ||
|
|
132120a88e | ||
|
|
c1ce9029d8 | ||
|
|
c079d2ab5d | ||
|
|
229a41557e | ||
|
|
934b2cd2d3 | ||
|
|
a1711bd399 | ||
|
|
a4d294015a | ||
|
|
660632ef6b |
@@ -0,0 +1,112 @@
|
||||
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 "# Hash checking alone ignores files this manifest does not list, and"
|
||||
echo "# the Xcode project compiles any source file present in the tree. So"
|
||||
echo "# also confirm nothing extra is present:"
|
||||
echo "# git status --porcelain --ignored # git checkout: must print nothing"
|
||||
echo "# or, for a tarball, diff this manifest's path list against find(1)."
|
||||
echo "# Full instructions: docs/VERIFYING-A-BUILD.md"
|
||||
echo "# The git tree hash above is the single value covering all tracked content:"
|
||||
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
|
||||
@@ -190,12 +190,19 @@ jobs:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v5
|
||||
|
||||
# Some runner images list only placeholder destinations (rows carrying
|
||||
# "error:" or "unavailable") or ship the selected Xcode without a
|
||||
# matching iOS simulator runtime, so this walks three paths in order:
|
||||
# a usable xcodebuild destination, an existing simctl device, and
|
||||
# finally creating a device from the newest installed iOS runtime.
|
||||
- name: Select available iPhone simulator
|
||||
id: destination
|
||||
run: |
|
||||
destinations=$(xcodebuild -project bitchat.xcodeproj -scheme "bitchat (iOS)" -showdestinations)
|
||||
set -uo pipefail
|
||||
destinations=$(xcodebuild -project bitchat.xcodeproj -scheme "bitchat (iOS)" -showdestinations 2>/dev/null || true)
|
||||
destination_id=$(awk -F'id:' '
|
||||
/platform:iOS Simulator/ && /name:iPhone/ && !found {
|
||||
/platform:iOS Simulator/ && /name:iPhone/ \
|
||||
&& !/error/ && !/unavailable/ && !found {
|
||||
value=$2
|
||||
sub(/,.*/, "", value)
|
||||
gsub(/^[[:space:]]+|[[:space:]]+$/, "", value)
|
||||
@@ -203,10 +210,47 @@ jobs:
|
||||
found=1
|
||||
}
|
||||
' <<< "$destinations")
|
||||
if [ -z "$destination_id" ]; then
|
||||
echo "::error::No available iPhone simulator destination found"
|
||||
exit 1
|
||||
|
||||
if [ -n "$destination_id" ]; then
|
||||
echo "Selected destination via xcodebuild -showdestinations: $destination_id"
|
||||
else
|
||||
echo "No usable iPhone destination in -showdestinations output; falling back to simctl"
|
||||
destination_id=$(xcrun simctl list devices available --json | jq -r '
|
||||
[.devices | to_entries[]
|
||||
| select(.key | contains("iOS"))
|
||||
| .value[]
|
||||
| select(.isAvailable and (.name | startswith("iPhone")))]
|
||||
| first.udid // empty')
|
||||
if [ -n "$destination_id" ]; then
|
||||
echo "Selected existing simctl device: $destination_id"
|
||||
else
|
||||
echo "No available iPhone simulator device; creating one"
|
||||
# Newest installed iOS runtime plus an iPhone device type that
|
||||
# runtime itself reports as supported, so the pair always match.
|
||||
create_spec=$(xcrun simctl list runtimes --json | jq -r '
|
||||
[.runtimes[] | select(.platform == "iOS" and .isAvailable)]
|
||||
| sort_by(.version | split(".") | map(tonumber))
|
||||
| last // empty
|
||||
| .identifier as $runtime
|
||||
| ([(.supportedDeviceTypes // [])[]
|
||||
| select(.productFamily == "iPhone"
|
||||
or (.name // "" | startswith("iPhone")))]
|
||||
| first.identifier // empty) as $devicetype
|
||||
| "\($devicetype) \($runtime)"')
|
||||
read -r devicetype runtime <<< "$create_spec" || true
|
||||
if [ -z "${devicetype:-}" ] || [ -z "${runtime:-}" ]; then
|
||||
echo "::error::No iPhone simulator destination found and none creatable (no installed iOS runtime with an iPhone device type)"
|
||||
exit 1
|
||||
fi
|
||||
destination_id=$(xcrun simctl create ci-iphone "$devicetype" "$runtime") || {
|
||||
echo "::error::simctl create failed for $devicetype on $runtime"
|
||||
exit 1
|
||||
}
|
||||
echo "Created simulator $destination_id ($devicetype, $runtime)"
|
||||
fi
|
||||
fi
|
||||
|
||||
echo "Using iPhone simulator destination id: $destination_id"
|
||||
echo "id=$destination_id" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Run iOS tests
|
||||
|
||||
+9
-4
@@ -34,13 +34,13 @@ bitchat is designed for private, account-free communication. This policy describ
|
||||
- A panic wipe deletes both stores.
|
||||
|
||||
5. **Recent public mesh messages and notices**
|
||||
- Signed public mesh messages may be kept in a protected local gossip archive for up to 15 minutes so they can cross mesh partitions and survive a short relaunch.
|
||||
- Signed public mesh messages may be kept in a protected local gossip archive for up to 6 hours so they can cross mesh partitions and survive a relaunch.
|
||||
- Public bulletin-board posts and deletion tombstones persist until the post's author-selected expiry, at most seven days. Both stores are bounded and panic-wipeable.
|
||||
- These items are public to the mesh or board where they are posted; they are not confidential messages.
|
||||
|
||||
6. **Media attachments**
|
||||
- Voice notes and images you send or receive can be stored under Application Support so they remain playable while referenced by the app.
|
||||
- Incoming media is subject to a 100 MB quota with oldest-file eviction. Media is deleted by panic wipe or app removal; some outgoing media can otherwise remain on disk.
|
||||
- Incoming media is subject to a 100 MB quota with oldest-file eviction. All stored media, sent and received, is also deleted once it is more than seven days old, and immediately by panic wipe or app removal.
|
||||
|
||||
7. **Optional location-channel state**
|
||||
- Your selected geohash channel, bookmarks, teleport flags, and bookmark display names are stored locally so the UI can restore them.
|
||||
@@ -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.
|
||||
@@ -114,14 +116,17 @@ No cryptographic system can protect content after a recipient reads, copies, scr
|
||||
- **In-memory chat timelines and active connections:** until the app closes or state is cleared.
|
||||
- **Queued outgoing private messages:** until acknowledged, dropped by bounded policy, or 24 hours, whichever comes first.
|
||||
- **Opaque courier envelopes:** until handed off, evicted by bounded policy, or 24 hours, whichever comes first.
|
||||
- **Recent public mesh gossip:** up to 15 minutes.
|
||||
- **Recent public mesh gossip:** up to 6 hours.
|
||||
- **Public board posts and tombstones:** until expiry, at most seven days.
|
||||
- **Groups, favorites, preferences, identity keys, bookmarks, and media:** until removed by the feature, panic wipe, quota eviction where applicable, or app removal.
|
||||
- **Media:** seven days, or sooner by quota eviction, panic wipe, or app removal.
|
||||
- **Groups, favorites, preferences, identity keys, and bookmarks:** until removed by the feature, panic wipe, or app removal.
|
||||
- **Nostr data:** according to the policies of the relays that receive it.
|
||||
|
||||
## Your Controls
|
||||
|
||||
- **Panic wipe:** Triple-tap the logo to synchronously cancel in-flight media work and clear local keys, sessions, preferences, groups, queues, carried mail, public archives, board data, and media managed by the app.
|
||||
- **Notification previews:** Hidden by default, so lock-screen alerts do not show message text, sender names, or geohashes. Full previews can be turned on in settings.
|
||||
- **Clearing a conversation:** Clearing the mesh timeline also deletes the recent public gossip this device had stored on disk.
|
||||
- **Feature controls:** Location channels, mesh bridge, internet gateway, and related internet behaviors can be disabled in the app. Some already-published relay data cannot be recalled.
|
||||
- **System permissions:** Bluetooth, location, microphone, camera, and photo-library access can be revoked in system settings.
|
||||
- **No account:** The project operates no account record for you to request or export.
|
||||
|
||||
@@ -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.
|
||||
@@ -18,7 +24,7 @@ This project is released into the public domain. See the [LICENSE](LICENSE) file
|
||||
- **Location-Based Channels**: Geographic chat rooms using geohash coordinates over global Nostr relays
|
||||
- **Intelligent Message Routing**: Automatically chooses best transport (Bluetooth → Nostr fallback)
|
||||
- **Decentralized Mesh Network**: Automatic peer discovery and multi-hop message relay over Bluetooth LE
|
||||
- **Privacy First**: No accounts, no phone numbers, no persistent identifiers
|
||||
- **Privacy First**: No accounts, no phone numbers, no servers. Note that the mesh does use a persistent per-device identifier derived from your identity key — see [the whitepaper](WHITEPAPER.md) on identity and metadata for what a nearby radio can observe
|
||||
- **Private Message End-to-End Encryption**: [Noise Protocol](https://noiseprotocol.org) for mesh, BitChat private envelopes for Nostr fallback
|
||||
- **IRC-Style Commands**: Familiar `/slap`, `/msg`, `/who` style interface
|
||||
- **Universal App**: Native support for iOS and macOS
|
||||
@@ -34,7 +40,7 @@ BitChat uses a **hybrid messaging architecture** with two complementary transpor
|
||||
- **Local Communication**: Direct peer-to-peer within Bluetooth range
|
||||
- **Multi-hop Relay**: Messages route through nearby devices (max 7 hops)
|
||||
- **No Internet Required**: Works completely offline in disaster scenarios
|
||||
- **Noise Protocol Encryption**: End-to-end encryption with forward secrecy
|
||||
- **Noise Protocol Encryption**: End-to-end encryption, with forward secrecy for live sessions (store-and-forward mail is sealed without it — see the whitepaper)
|
||||
- **Binary Protocol**: Compact packet format optimized for Bluetooth LE constraints
|
||||
- **Automatic Discovery**: Peer discovery and connection management
|
||||
- **Adaptive Power**: Battery-optimized duty cycling
|
||||
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
# Security policy
|
||||
|
||||
bitchat is a security-focused messenger, and reports about its security are taken seriously. This page says how to report, what counts as a vulnerability here, and what to expect.
|
||||
|
||||
## Reporting a vulnerability
|
||||
|
||||
**Use GitHub's private vulnerability reporting:** [Report a vulnerability](https://github.com/permissionlesstech/bitchat/security/advisories/new) (Security tab → "Report a vulnerability").
|
||||
|
||||
Please do not open a public issue for anything that could put people at risk before a fix ships. bitchat is used by people in hostile network environments; a public proof-of-concept can be acted on faster than a patch can reach them.
|
||||
|
||||
A useful report says what an attacker can do, against which build (App Store version or commit hash), and how to reproduce it. A failing test or a packet capture is worth more than speculation about impact.
|
||||
|
||||
## What to expect
|
||||
|
||||
This is a volunteer-maintained project. The aim is to acknowledge reports within a week and to move on confirmed vulnerabilities immediately — historically, confirmed protocol and key-handling issues have been fixed within days. You'll be kept in the loop in the advisory thread, and credited in the fix unless you'd rather not be. There is no bug bounty.
|
||||
|
||||
## Supported versions
|
||||
|
||||
Fixes ship to the latest App Store release and `main`. Older releases are not patched; the fix is to update.
|
||||
|
||||
## Scope
|
||||
|
||||
In scope — the properties the app promises:
|
||||
|
||||
- Confidentiality and integrity of private messages and media (Noise sessions over BLE; over Nostr, bitchat's own ephemeral private-envelope format — a proprietary scheme, *not* NIP-17/NIP-44/NIP-59, see `WHITEPAPER.md`)
|
||||
- Identity: key handling, verification, impersonation, session binding
|
||||
- The panic wipe actually destroying what it claims to destroy
|
||||
- Metadata exposure beyond what the documentation already discloses (see `PRIVACY_POLICY.md` and `docs/privacy-assessment.md`)
|
||||
- Downgrade paths: anything that silently moves traffic from an encrypted path to a plaintext one
|
||||
- Tor routing: anything that makes traffic bypass Tor while the Tor preference is on
|
||||
- Supply-chain integrity of the source and its vendored binaries (see `docs/VERIFYING-A-BUILD.md`)
|
||||
|
||||
Out of scope — documented design properties, not vulnerabilities:
|
||||
|
||||
- Public visibility of mesh announces and geohash channels: broadcast content, nicknames, and public keys are public by design
|
||||
- Bluetooth proximity being observable: anyone in radio range can tell a BLE device is present
|
||||
- Mesh flooding/relay behavior inherent to a broadcast mesh (rate limits exist; the topology is what it is)
|
||||
- Behavior of third-party Nostr relays
|
||||
- Denial of service requiring physical proximity, and battery-drain attacks in general
|
||||
|
||||
If you're unsure whether something is in scope, report it privately anyway — a false alarm costs a few minutes; a real issue reported publicly can cost much more.
|
||||
|
||||
## Verifying what you're running
|
||||
|
||||
If your concern is that the app or source you have has been tampered with, that has its own document: `docs/VERIFYING-A-BUILD.md`.
|
||||
+12
-5
@@ -18,7 +18,7 @@ bitchat is a decentralized, peer-to-peer messaging application for secure, priva
|
||||
* **Authentication:** peers are identified by cryptographic keys; announcements are signed and verified.
|
||||
* **Resilience:** the network functions in lossy, low-bandwidth, partitioned environments with churning membership.
|
||||
* **Eventual delivery:** a message to an out-of-range peer should still arrive — relayed by the mesh, carried by a moving person, or resting on an internet relay — within a bounded retention window.
|
||||
* **Ephemerality by default:** no plaintext message content is ever written to disk. Everything the store-and-forward stack persists is either sealed ciphertext or already-public broadcast traffic, and all of it dies with the panic wipe.
|
||||
* **Ephemerality by default:** conversation timelines live in memory only. Everything the store-and-forward stack persists is either sealed ciphertext or already-public broadcast traffic, and all of it dies with the panic wipe. Media is the exception: accepted images and voice notes are written to disk unsealed, protected by the platform's data-protection class rather than by app-layer encryption, and bounded by a storage quota.
|
||||
|
||||
## 2. Architecture Overview
|
||||
|
||||
@@ -36,13 +36,17 @@ Each device holds two long-term key pairs in the Keychain:
|
||||
* a **Curve25519 static key** for Noise key agreement — its SHA-256 fingerprint is the peer's stable identity, and
|
||||
* an **Ed25519 signing key** for packet signatures.
|
||||
|
||||
On the mesh, peers appear under short ephemeral IDs derived per session; favoriting pins the full Noise public key so identity survives across sessions. Mutual favorites also exchange Nostr public keys for the internet path. Optional QR verification binds a nickname to a fingerprint in person.
|
||||
On the mesh, peers appear under a short 8-byte peer ID. That ID is **not ephemeral**: it is the first 8 bytes of the SHA-256 fingerprint of the device's Noise static key, so it is stable across sessions, reboots, and reinstalls that preserve the keychain, and it changes only when the identity itself is replaced by a panic wipe. Favoriting pins the full Noise public key so identity survives across sessions. Mutual favorites also exchange Nostr public keys for the internet path. Optional QR verification binds a nickname to a fingerprint in person.
|
||||
|
||||
Signed announcements additionally carry the nickname, the Noise static public key, and the Ed25519 signing public key in cleartext (§4.5), so a passive receiver in radio range can link a device across time and place regardless of the peer ID. Unlinkable presence is not a property this protocol currently provides; see §9.
|
||||
|
||||
## 4. BLE Mesh Layer
|
||||
|
||||
### 4.1 Packet Format
|
||||
|
||||
A compact binary header (version, type, TTL, timestamp, flags) is followed by an 8-byte sender ID, an optional 8-byte recipient ID, the payload, and an optional Ed25519 signature. Version 2 packets may carry an explicit source route. Signatures exclude the TTL byte so relays can decrement it without invalidating them. Packets other than fragments are padded toward uniform sizes.
|
||||
A compact binary header (version, type, TTL, timestamp, flags) is followed by an 8-byte sender ID, an optional 8-byte recipient ID, the payload, and an optional Ed25519 signature. Version 2 packets may carry an explicit source route. Signatures exclude the TTL byte so relays can decrement it without invalidating them.
|
||||
|
||||
Only `noiseEncrypted` and `noiseHandshake` packets are padded, toward 256/512/1024/2048-byte buckets; every other type — public messages, announcements, board posts, group messages, fragments, files, and voice frames — goes out at its natural length. Padding is PKCS#7-style with pad bytes equal to the pad length, and because that length must fit one byte, a frame needing more than 255 bytes to reach its bucket is emitted unpadded. Payload length is therefore observable for most traffic.
|
||||
|
||||
### 4.2 Flood Control
|
||||
|
||||
@@ -124,11 +128,11 @@ Bare local counters (deposits, handovers, sprays, opens, outbox flushes and drop
|
||||
|
||||
## 8. Security Considerations
|
||||
|
||||
* **Relay nodes** cannot read private traffic; they forward padded, opaque ciphertext.
|
||||
* **Relay nodes** cannot read private traffic; they forward opaque ciphertext. Padding applies to Noise frames only (§4.1), so other packet types relay at their natural length.
|
||||
* **Couriers** are quota-bounded mailbags. A malicious courier can drop mail (redundant copies and deposit retry mitigate this) but cannot read it, link it across days, or amplify it — copy budgets are capped and every envelope is validated against size and lifetime policy on deposit.
|
||||
* **Flooding abuse** is bounded by TTL clamps, deduplication, per-depositor quotas, connect-rate limits, and announce-rate limiting.
|
||||
* **Replay** of public broadcasts is bounded by the 6-hour acceptance window plus deduplication; private payloads are protected by Noise nonces.
|
||||
* **Metadata.** BLE proximity is inherently observable; ephemeral IDs and daily-rotating courier tags limit long-term correlation. Nostr traffic can ride Tor.
|
||||
* **Metadata is the weakest part of this design, and the peer ID does not help.** The 8-byte sender ID in every packet header is derived from a never-rotating key (§3), and announcements publish the static keys and nickname in cleartext, so a passive listener can enumerate participants and follow a device between places. Announcements also carry up to ten direct-neighbor IDs (§4.3), which hands a single sniffer the local adjacency graph. Origin packets leave at the default TTL, so hop distance identifies the originator. Daily-rotating courier tags do limit correlation of carried mail, and Nostr traffic can ride Tor. Addressing the radio-layer exposure is future work (§9).
|
||||
* **No forward secrecy for sealed mail or Nostr private envelopes** (§5.2–5.3) means compromise of a recipient's static key can expose retained ciphertext addressed to that key.
|
||||
|
||||
## 9. Future Work
|
||||
@@ -137,6 +141,9 @@ Bare local counters (deposits, handovers, sprays, opens, outbox flushes and drop
|
||||
* Couriered media beyond the 16 KiB text cap.
|
||||
* Probabilistic relay and edge-of-network TTL boosting for very dense and very sparse graphs.
|
||||
* Multi-hop courier routing informed by encounter history.
|
||||
* **Rotating on-air identity.** Epoch-rotating peer IDs, with static-key disclosure moved inside the encrypted handshake and mutual favorites recognising each other through a tag derived from their shared secret, so presence stops being linkable across sessions (§3, §8).
|
||||
* **Padding for non-Noise packet types**, and closing the gap where a frame needing more than 255 bytes of padding is emitted unpadded (§4.1).
|
||||
* Making the neighbor list in announcements optional, or restricted to authenticated links (§4.3).
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -152,11 +152,21 @@ final class AppRuntime: ObservableObject {
|
||||
NetworkActivationService.shared.start()
|
||||
GeohashPresenceService.shared.start()
|
||||
checkForSharedContent()
|
||||
expireAgedMedia()
|
||||
|
||||
record(.launched)
|
||||
record(.startupCompleted)
|
||||
}
|
||||
|
||||
/// Drops media that has outlived the retention window. Off the main thread
|
||||
/// and best-effort: the sweep walks the media tree, and nothing at launch
|
||||
/// depends on its result.
|
||||
private func expireAgedMedia() {
|
||||
Task(priority: .utility) {
|
||||
BLEIncomingFileStore().expireAgedMedia()
|
||||
}
|
||||
}
|
||||
|
||||
func handleOpenURL(_ url: URL) {
|
||||
record(.openedURL(url.absoluteString))
|
||||
|
||||
@@ -319,6 +329,16 @@ private extension AppRuntime {
|
||||
}
|
||||
.store(in: &cancellables)
|
||||
|
||||
NotificationCenter.default.publisher(for: .TorBootstrapDidStall)
|
||||
.receive(on: DispatchQueue.main)
|
||||
.sink { [weak self] _ in
|
||||
guard self?.chatViewModel.networkActivationAllowed == true
|
||||
else { return }
|
||||
self?.record(.torLifecycleChanged(.bootstrapDidStall))
|
||||
self?.chatViewModel.handleTorBootstrapDidStall()
|
||||
}
|
||||
.store(in: &cancellables)
|
||||
|
||||
NotificationCenter.default.publisher(for: .TorUserPreferenceChanged)
|
||||
.receive(on: DispatchQueue.main)
|
||||
.sink { [weak self] notification in
|
||||
|
||||
@@ -442,6 +442,40 @@ final class ConversationStore: ObservableObject {
|
||||
@discardableResult
|
||||
func setDeliveryStatus(_ status: DeliveryStatus, forMessageID messageID: String) -> Bool {
|
||||
guard let ids = conversationIDsByMessageID[messageID] else { return false }
|
||||
return applyDeliveryStatus(status, forMessageID: messageID, among: ids)
|
||||
}
|
||||
|
||||
/// Applies an authenticated delivery/read receipt only to the supplied
|
||||
/// direct-conversation aliases. A colliding message ID in another peer's
|
||||
/// conversation (or a public timeline) must not inherit the receipt.
|
||||
///
|
||||
/// Stable and ephemeral aliases can temporarily hold the same message
|
||||
/// instance during handoff. The shared helper republishes every targeted
|
||||
/// alias even when the first mutation already changed that instance.
|
||||
@discardableResult
|
||||
func setDeliveryStatus(
|
||||
_ status: DeliveryStatus,
|
||||
forMessageID messageID: String,
|
||||
inDirectPeerAliases peerIDs: Set<PeerID>
|
||||
) -> Bool {
|
||||
guard !peerIDs.isEmpty,
|
||||
let indexedIDs = conversationIDsByMessageID[messageID] else {
|
||||
return false
|
||||
}
|
||||
let allowedIDs = Set(peerIDs.map { ConversationID.directPeer($0) })
|
||||
return applyDeliveryStatus(
|
||||
status,
|
||||
forMessageID: messageID,
|
||||
among: indexedIDs.intersection(allowedIDs)
|
||||
)
|
||||
}
|
||||
|
||||
private func applyDeliveryStatus(
|
||||
_ status: DeliveryStatus,
|
||||
forMessageID messageID: String,
|
||||
among ids: Set<ConversationID>
|
||||
) -> Bool {
|
||||
guard !ids.isEmpty else { return false }
|
||||
var applied = false
|
||||
var skipped: [ConversationID] = []
|
||||
for id in ids {
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
//
|
||||
// PrivacyScreen.swift
|
||||
// bitchat
|
||||
//
|
||||
// This is free and unencumbered software released into the public domain.
|
||||
// For more information, see <https://unlicense.org>
|
||||
//
|
||||
|
||||
#if os(iOS)
|
||||
import UIKit
|
||||
|
||||
/// Covers the window while the app is not frontmost, so the snapshot iOS takes
|
||||
/// for the app switcher shows a placeholder instead of the open conversation.
|
||||
///
|
||||
/// The cover is added on `willResignActive` and removed on `didBecomeActive`.
|
||||
/// Both are deliberately UIKit notifications rather than SwiftUI's `scenePhase`:
|
||||
/// the snapshot is captured shortly after `willResignActive`, and adding an
|
||||
/// opaque subview to the window synchronously in that callback is the only way
|
||||
/// to guarantee it is in the render tree before the capture. A SwiftUI overlay
|
||||
/// driven by state may not have been laid out yet.
|
||||
///
|
||||
/// Panic wipe separately deletes any snapshots already on disk; this keeps new
|
||||
/// ones from containing anything worth deleting.
|
||||
final class PrivacyScreen {
|
||||
static let shared = PrivacyScreen()
|
||||
|
||||
private var cover: UIView?
|
||||
private var observers: [NSObjectProtocol] = []
|
||||
|
||||
private init() {}
|
||||
|
||||
/// Idempotent: repeated calls do not stack observers.
|
||||
///
|
||||
/// `queue: nil` is required, not incidental. Passing an `OperationQueue`
|
||||
/// would enqueue the handler to run in a later runloop turn, which the
|
||||
/// snapshot can beat; with no queue the block runs synchronously on the
|
||||
/// thread that posted the notification — the main thread, for UIApplication
|
||||
/// lifecycle notifications.
|
||||
func install() {
|
||||
guard observers.isEmpty else { return }
|
||||
let center = NotificationCenter.default
|
||||
observers = [
|
||||
center.addObserver(
|
||||
forName: UIApplication.willResignActiveNotification,
|
||||
object: nil,
|
||||
queue: nil
|
||||
) { _ in
|
||||
PrivacyScreen.shared.show()
|
||||
},
|
||||
center.addObserver(
|
||||
forName: UIApplication.didBecomeActiveNotification,
|
||||
object: nil,
|
||||
queue: nil
|
||||
) { _ in
|
||||
PrivacyScreen.shared.hide()
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
private func show() {
|
||||
guard cover == nil, let window = Self.activeWindow() else { return }
|
||||
|
||||
// Opaque rather than a blur: blurred large text can stay partly
|
||||
// legible, and the snapshot is stored on disk.
|
||||
let view = UIView(frame: window.bounds)
|
||||
view.backgroundColor = .systemBackground
|
||||
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
|
||||
|
||||
let label = UILabel()
|
||||
label.text = "bitchat"
|
||||
label.font = .monospacedSystemFont(ofSize: 22, weight: .medium)
|
||||
label.textColor = .secondaryLabel
|
||||
label.translatesAutoresizingMaskIntoConstraints = false
|
||||
view.addSubview(label)
|
||||
NSLayoutConstraint.activate([
|
||||
label.centerXAnchor.constraint(equalTo: view.centerXAnchor),
|
||||
label.centerYAnchor.constraint(equalTo: view.centerYAnchor)
|
||||
])
|
||||
|
||||
window.addSubview(view)
|
||||
cover = view
|
||||
}
|
||||
|
||||
private func hide() {
|
||||
cover?.removeFromSuperview()
|
||||
cover = nil
|
||||
}
|
||||
|
||||
private static func activeWindow() -> UIWindow? {
|
||||
UIApplication.shared.connectedScenes
|
||||
.compactMap { $0 as? UIWindowScene }
|
||||
.flatMap(\.windows)
|
||||
.first { $0.isKeyWindow } ??
|
||||
UIApplication.shared.connectedScenes
|
||||
.compactMap { $0 as? UIWindowScene }
|
||||
.flatMap(\.windows)
|
||||
.first
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -74,7 +74,10 @@ final class AppDelegate: NSObject, UIApplicationDelegate {
|
||||
weak var runtime: AppRuntime?
|
||||
|
||||
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
|
||||
true
|
||||
// Installed before the first resign-active so the app-switcher snapshot
|
||||
// never captures an open conversation.
|
||||
PrivacyScreen.shared.install()
|
||||
return true
|
||||
}
|
||||
|
||||
func applicationWillTerminate(_ application: UIApplication) {
|
||||
|
||||
@@ -14,18 +14,22 @@
|
||||
///
|
||||
/// ## Overview
|
||||
/// BitChat's identity system separates concerns across three distinct layers:
|
||||
/// 1. **Ephemeral Identity**: Short-lived, rotatable peer IDs for privacy
|
||||
/// 1. **Network Identity**: the 8-byte peer ID seen on air
|
||||
/// 2. **Cryptographic Identity**: Long-term Noise static keys for security
|
||||
/// 3. **Social Identity**: User-assigned names and trust relationships
|
||||
/// 3. **Social Identity**: assigned names and trust relationships
|
||||
///
|
||||
/// This separation allows users to maintain stable cryptographic identities
|
||||
/// while frequently rotating their network identifiers for privacy.
|
||||
/// The layers are separate concerns, but they are not independent: the network
|
||||
/// identity is *derived* from the cryptographic one, so it does not provide
|
||||
/// unlinkability. Rotating peer IDs would be a change to this model, not a
|
||||
/// description of it — see the note below.
|
||||
///
|
||||
/// ## Three-Layer Architecture
|
||||
///
|
||||
/// ### Layer 1: Ephemeral Identity
|
||||
/// - Random 8-byte peer IDs that rotate periodically
|
||||
/// - Provides network-level privacy and prevents tracking
|
||||
/// ### Layer 1: Network Identity
|
||||
/// - 8-byte peer ID = first 8 bytes of the Noise static key fingerprint
|
||||
/// - **Not ephemeral and not rotating.** It is stable across sessions and
|
||||
/// reboots, and changes only when the underlying identity is replaced by a
|
||||
/// panic wipe. A passive observer can use it to track a device.
|
||||
/// - Changes don't affect cryptographic relationships
|
||||
/// - Includes handshake state tracking
|
||||
///
|
||||
@@ -33,7 +37,7 @@
|
||||
/// - Based on Noise Protocol static key pairs
|
||||
/// - Fingerprint derived from SHA256 of public key
|
||||
/// - Enables end-to-end encryption and authentication
|
||||
/// - Persists across peer ID rotations
|
||||
/// - The root of the peer ID above, and never rotated on a schedule
|
||||
///
|
||||
/// ### Layer 3: Social Identity
|
||||
/// - User-assigned names (petnames) for contacts
|
||||
@@ -44,10 +48,13 @@
|
||||
/// ## Privacy Design
|
||||
/// The model is designed with privacy-first principles:
|
||||
/// - No mandatory persistent storage
|
||||
/// - Optional identity caching with user consent
|
||||
/// - Ephemeral IDs prevent long-term tracking
|
||||
/// - Optional identity caching with explicit consent
|
||||
/// - Social mappings stored locally only
|
||||
///
|
||||
/// It does **not** currently prevent long-term tracking by a passive radio
|
||||
/// observer: the peer ID is stable (Layer 1) and signed announcements carry the
|
||||
/// static keys and nickname in cleartext.
|
||||
///
|
||||
/// ## Trust Model
|
||||
/// Four levels of trust:
|
||||
/// 1. **Unknown**: New or unverified peers
|
||||
@@ -56,17 +63,17 @@
|
||||
/// 4. **Verified**: Cryptographic verification completed
|
||||
///
|
||||
/// ## Identity Resolution
|
||||
/// When a peer rotates their ephemeral ID:
|
||||
/// When a peer's ID changes (a panic wipe on their side, or a future rotation):
|
||||
/// 1. Cryptographic handshake reveals their fingerprint
|
||||
/// 2. System looks up social identity by fingerprint
|
||||
/// 3. UI seamlessly maintains user relationships
|
||||
/// 3. UI seamlessly maintains existing relationships
|
||||
/// 4. Historical messages remain properly attributed
|
||||
///
|
||||
/// ## Conflict Resolution
|
||||
/// Handles edge cases like:
|
||||
/// - Multiple peers claiming same nickname
|
||||
/// - Nickname changes and conflicts
|
||||
/// - Identity rotation during active chats
|
||||
/// - Identity replacement during active chats
|
||||
/// - Network partitions and rejoins
|
||||
///
|
||||
/// ## Usage Example
|
||||
@@ -85,8 +92,12 @@ import BitFoundation
|
||||
|
||||
// MARK: - Three-Layer Identity Model
|
||||
|
||||
/// Represents the ephemeral layer of identity - short-lived peer IDs that provide network privacy.
|
||||
/// These IDs rotate periodically to prevent tracking while maintaining cryptographic relationships.
|
||||
/// Represents the network layer of identity — the peer ID seen on air, plus the
|
||||
/// handshake state tracked against it.
|
||||
///
|
||||
/// Named "ephemeral" for historical reasons; the peer ID is in fact stable,
|
||||
/// being derived from the Noise static key fingerprint. It does not rotate and
|
||||
/// does not prevent tracking.
|
||||
struct EphemeralIdentity {
|
||||
var handshakeState: HandshakeState
|
||||
}
|
||||
@@ -99,8 +110,9 @@ enum HandshakeState {
|
||||
}
|
||||
|
||||
/// Represents the cryptographic layer of identity - the stable Noise Protocol static key pair.
|
||||
/// This identity persists across ephemeral ID rotations and enables secure communication.
|
||||
/// The fingerprint serves as the permanent identifier for a peer's cryptographic identity.
|
||||
/// This identity outlives any change to a peer's network ID and enables secure communication.
|
||||
/// The fingerprint serves as the permanent identifier for a peer's cryptographic identity, and
|
||||
/// its first 8 bytes are the peer ID broadcast on the mesh.
|
||||
struct CryptographicIdentity: Codable {
|
||||
let fingerprint: String // SHA256 of public key
|
||||
let publicKey: Data // Noise static public key
|
||||
|
||||
+3534
-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,60 @@ 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()
|
||||
// A relay queued while Tor bootstraps would otherwise reconnect when
|
||||
// the queue drains, overriding the explicit removal.
|
||||
pendingTorConnectionURLs.subtract(urls)
|
||||
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 +1418,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)
|
||||
}
|
||||
}
|
||||
@@ -38,11 +38,15 @@
|
||||
/// 7. **Decoding**: Binary data parsed back to message objects
|
||||
///
|
||||
/// ## Security Considerations
|
||||
/// - Message padding (to 256/512/1024/2048-byte blocks) obscures actual content length
|
||||
/// - Noise frames are padded (to 256/512/1024/2048-byte blocks) to obscure
|
||||
/// content length; other packet types are not padded, so their payload
|
||||
/// length is observable
|
||||
/// - Randomized relay jitter reduces the traffic-analysis signal; there is no
|
||||
/// cover traffic or per-message timing obfuscation
|
||||
/// - Integration with Noise Protocol for E2E encryption
|
||||
/// - No persistent identifiers in protocol headers
|
||||
/// - The 8-byte sender ID in every header IS a persistent identifier: it is
|
||||
/// derived from the long-lived Noise static key and rotates only on a panic
|
||||
/// wipe. Treat headers as linkable across sessions.
|
||||
///
|
||||
/// ## Message Types
|
||||
/// - **Announce/Leave**: Peer presence notifications
|
||||
|
||||
@@ -114,6 +114,9 @@ struct BLEIncomingFileStore: @unchecked Sendable {
|
||||
}
|
||||
|
||||
private static let defaultQuotaBytes: Int64 = 100 * 1024 * 1024
|
||||
/// How long managed media may stay on disk. Bounds by age what the quota
|
||||
/// only bounds by size; see `expireAgedMedia(retention:)`.
|
||||
static let defaultMediaRetention: TimeInterval = 7 * 24 * 60 * 60
|
||||
/// Kept outside `files/` so deleting the media tree cannot erase the
|
||||
/// fail-closed startup decision before the full panic has committed.
|
||||
private static let panicRecoveryPendingMarkerFileName =
|
||||
@@ -569,6 +572,84 @@ struct BLEIncomingFileStore: @unchecked Sendable {
|
||||
}
|
||||
}
|
||||
|
||||
/// Deletes managed media older than `retention`, across both incoming and
|
||||
/// outgoing directories, and reports how many files went away.
|
||||
///
|
||||
/// The quota sweep above only bounds *size*, and only for incoming files,
|
||||
/// so a received photo or a sent voice note could sit on disk unbounded in
|
||||
/// time — long outliving the conversation it belonged to, which is what a
|
||||
/// seized device gives up. This bounds media by age instead, on the same
|
||||
/// principle as the courier envelope and gossip archive lifetimes.
|
||||
///
|
||||
/// Honors the same exclusions as quota eviction: in-flight live captures
|
||||
/// and files reserved by an in-progress delivery or deletion are left
|
||||
/// alone regardless of age.
|
||||
@discardableResult
|
||||
func expireAgedMedia(retention: TimeInterval = Self.defaultMediaRetention) -> Int {
|
||||
guard retention > 0 else { return 0 }
|
||||
|
||||
payloadCoordination.lock.lock()
|
||||
defer { payloadCoordination.lock.unlock() }
|
||||
|
||||
let cutoff = dateProvider().addingTimeInterval(-retention)
|
||||
let activeDeletionPaths = payloadCoordination
|
||||
.deletionReservations.values.reduce(into: Set<String>()) {
|
||||
$0.formUnion($1)
|
||||
}
|
||||
let protectedPaths = activeDeletionPaths.union(
|
||||
payloadCoordination.pendingDeliveryPaths
|
||||
)
|
||||
|
||||
var removed = 0
|
||||
do {
|
||||
let base = try filesDirectory()
|
||||
for subdirectory in Self.mediaSubdirectories {
|
||||
let dir = base.appendingPathComponent(subdirectory, isDirectory: true)
|
||||
guard fileManager.fileExists(atPath: dir.path) else { continue }
|
||||
guard let contents = try? fileManager.contentsOfDirectory(
|
||||
at: dir,
|
||||
includingPropertiesForKeys: [.contentModificationDateKey],
|
||||
options: [.skipsHiddenFiles]
|
||||
) else { continue }
|
||||
|
||||
for fileURL in contents {
|
||||
guard let modified = try? fileURL.resourceValues(
|
||||
forKeys: [.contentModificationDateKey]
|
||||
).contentModificationDate else { continue }
|
||||
guard modified < cutoff else { continue }
|
||||
guard !fileURL.lastPathComponent.hasPrefix(Self.liveCapturePrefix) else { continue }
|
||||
guard !protectedPaths.contains(
|
||||
fileURL.standardizedFileURL.path
|
||||
) else { continue }
|
||||
|
||||
do {
|
||||
try fileManager.removeItem(at: fileURL)
|
||||
removed += 1
|
||||
} catch {
|
||||
SecureLogger.warning(
|
||||
"⚠️ Failed to expire aged media file: \(error)",
|
||||
category: .security
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
SecureLogger.warning(
|
||||
"⚠️ Could not expire aged media: \(error)",
|
||||
category: .security
|
||||
)
|
||||
return removed
|
||||
}
|
||||
|
||||
if removed > 0 {
|
||||
SecureLogger.info(
|
||||
"🗑️ Expired \(removed) media file(s) older than the retention window",
|
||||
category: .security
|
||||
)
|
||||
}
|
||||
return removed
|
||||
}
|
||||
|
||||
private func filesDirectory() throws -> URL {
|
||||
let filesDir = try rootDirectory().appendingPathComponent("files", isDirectory: true)
|
||||
try fileManager.createDirectory(at: filesDir, withIntermediateDirectories: true, attributes: nil)
|
||||
|
||||
@@ -5,6 +5,20 @@ struct BLELocalIdentitySnapshot: Equatable, Sendable {
|
||||
let peerID: PeerID
|
||||
let peerIDData: Data
|
||||
let nickname: String
|
||||
/// Runtime-toggled capability bits (e.g. the internet-gateway toggle)
|
||||
/// ORed into `PeerCapabilities.localSupported` for every announce.
|
||||
let runtimeCapabilities: PeerCapabilities
|
||||
/// Rendezvous cell advertised while bridging; rides announces only
|
||||
/// while the `.bridge` capability is enabled.
|
||||
let bridgeGeohash: String?
|
||||
|
||||
var advertisedCapabilities: PeerCapabilities {
|
||||
PeerCapabilities.localSupported.union(runtimeCapabilities)
|
||||
}
|
||||
|
||||
var advertisedBridgeGeohash: String? {
|
||||
runtimeCapabilities.contains(.bridge) ? bridgeGeohash : nil
|
||||
}
|
||||
}
|
||||
|
||||
/// Lock-backed local identity state shared by the transport's message,
|
||||
@@ -12,8 +26,8 @@ struct BLELocalIdentitySnapshot: Equatable, Sendable {
|
||||
///
|
||||
/// `peerID` and its binary wire representation must change as one unit during
|
||||
/// panic rotation. A snapshot also gives announce construction one consistent
|
||||
/// view of the nickname and identity instead of reading three independently
|
||||
/// mutable properties across queues.
|
||||
/// view of the nickname, identity, and advertised capabilities instead of
|
||||
/// reading independently mutable properties across queues.
|
||||
final class BLELocalIdentityStateStore: @unchecked Sendable {
|
||||
private let lock = NSLock()
|
||||
private var state: BLELocalIdentitySnapshot
|
||||
@@ -25,7 +39,9 @@ final class BLELocalIdentityStateStore: @unchecked Sendable {
|
||||
state = BLELocalIdentitySnapshot(
|
||||
peerID: peerID,
|
||||
peerIDData: Data(hexString: peerID.id) ?? Data(),
|
||||
nickname: nickname
|
||||
nickname: nickname,
|
||||
runtimeCapabilities: [],
|
||||
bridgeGeohash: nil
|
||||
)
|
||||
}
|
||||
|
||||
@@ -38,7 +54,9 @@ final class BLELocalIdentityStateStore: @unchecked Sendable {
|
||||
state = BLELocalIdentitySnapshot(
|
||||
peerID: state.peerID,
|
||||
peerIDData: state.peerIDData,
|
||||
nickname: nickname
|
||||
nickname: nickname,
|
||||
runtimeCapabilities: state.runtimeCapabilities,
|
||||
bridgeGeohash: state.bridgeGeohash
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -48,8 +66,48 @@ final class BLELocalIdentityStateStore: @unchecked Sendable {
|
||||
state = BLELocalIdentitySnapshot(
|
||||
peerID: peerID,
|
||||
peerIDData: Data(hexString: peerID.id) ?? Data(),
|
||||
nickname: state.nickname
|
||||
nickname: state.nickname,
|
||||
runtimeCapabilities: state.runtimeCapabilities,
|
||||
bridgeGeohash: state.bridgeGeohash
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Flips a runtime capability bit. Returns whether anything changed.
|
||||
@discardableResult
|
||||
func setCapability(_ capability: PeerCapabilities, enabled: Bool) -> Bool {
|
||||
lock.withLock {
|
||||
var capabilities = state.runtimeCapabilities
|
||||
if enabled {
|
||||
capabilities.insert(capability)
|
||||
} else {
|
||||
capabilities.remove(capability)
|
||||
}
|
||||
guard capabilities != state.runtimeCapabilities else { return false }
|
||||
state = BLELocalIdentitySnapshot(
|
||||
peerID: state.peerID,
|
||||
peerIDData: state.peerIDData,
|
||||
nickname: state.nickname,
|
||||
runtimeCapabilities: capabilities,
|
||||
bridgeGeohash: state.bridgeGeohash
|
||||
)
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the bridged rendezvous cell. Returns whether anything changed.
|
||||
@discardableResult
|
||||
func setBridgeGeohash(_ cell: String?) -> Bool {
|
||||
lock.withLock {
|
||||
guard cell != state.bridgeGeohash else { return false }
|
||||
state = BLELocalIdentitySnapshot(
|
||||
peerID: state.peerID,
|
||||
peerIDData: state.peerIDData,
|
||||
nickname: state.nickname,
|
||||
runtimeCapabilities: state.runtimeCapabilities,
|
||||
bridgeGeohash: cell
|
||||
)
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import BitFoundation
|
||||
import Foundation
|
||||
|
||||
struct BLEMeshPingProbe {
|
||||
let peerID: PeerID
|
||||
let sentAt: Date
|
||||
let lifecycleGeneration: UInt64
|
||||
let completion: @MainActor (MeshPingResult?) -> Void
|
||||
let timeout: DispatchWorkItem
|
||||
}
|
||||
|
||||
/// Engine-confined /ping diagnostics state: outstanding probes keyed by
|
||||
/// their unguessable nonce, plus the inbound response budget.
|
||||
///
|
||||
/// The budget is keyed by the ingress link (the directly connected peer
|
||||
/// that delivered the packet), never the packet-claimed sender: pings are
|
||||
/// unsigned, so the claimed sender is attacker-controlled and rotating it
|
||||
/// would reset the budget, turning a directed unencrypted probe into an
|
||||
/// amplification primitive.
|
||||
///
|
||||
/// Pure state — the transport owns packet I/O, timers, and main-actor
|
||||
/// completion delivery around it.
|
||||
struct BLEMeshPingTracker {
|
||||
private var pendingProbes: [Data: BLEMeshPingProbe] = [:]
|
||||
private var responseLimiter = SyncResponseRateLimiter(
|
||||
maxResponses: TransportConfig.meshPingInboundMaxPerLink,
|
||||
window: TransportConfig.meshPingInboundWindowSeconds
|
||||
)
|
||||
|
||||
mutating func register(_ probe: BLEMeshPingProbe, nonce: Data) {
|
||||
pendingProbes[nonce] = probe
|
||||
}
|
||||
|
||||
/// Resolves a pong against its outstanding probe. The echoed nonce plus
|
||||
/// the sender check bind the reply to the probed peer.
|
||||
mutating func resolve(nonce: Data, from peerID: PeerID) -> BLEMeshPingProbe? {
|
||||
guard pendingProbes[nonce]?.peerID == peerID else { return nil }
|
||||
return pendingProbes.removeValue(forKey: nonce)
|
||||
}
|
||||
|
||||
/// Removes a timed-out probe so its completion can fire once with nil.
|
||||
mutating func expire(nonce: Data) -> BLEMeshPingProbe? {
|
||||
pendingProbes.removeValue(forKey: nonce)
|
||||
}
|
||||
|
||||
/// Whether an inbound ping delivered by this link is within budget.
|
||||
mutating func shouldRespond(toLink linkPeerID: PeerID, now: Date) -> Bool {
|
||||
responseLimiter.shouldRespond(to: linkPeerID, now: now)
|
||||
}
|
||||
|
||||
/// Drops all probes and restores a fresh response budget (panic wipe).
|
||||
/// Returns the orphaned timeout work items for the caller to cancel.
|
||||
mutating func reset() -> [DispatchWorkItem] {
|
||||
let timeouts = pendingProbes.values.map(\.timeout)
|
||||
pendingProbes.removeAll()
|
||||
responseLimiter = SyncResponseRateLimiter(
|
||||
maxResponses: TransportConfig.meshPingInboundMaxPerLink,
|
||||
window: TransportConfig.meshPingInboundWindowSeconds
|
||||
)
|
||||
return timeouts
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import BitFoundation
|
||||
import Foundation
|
||||
|
||||
/// Lock-backed shared ownership of the peer registry, readable from any
|
||||
/// queue or the main actor without hopping onto a transport queue.
|
||||
///
|
||||
/// Mutations stay serialized by the transport (they only run on its
|
||||
/// queues), so the lock's job is to let the main actor answer questions
|
||||
/// like `isPeerConnected` without blocking behind in-flight transport
|
||||
/// work. Every `BLEPeerRegistry` mutation is a single whole-transition
|
||||
/// method, so a reader between two mutations always observes a valid
|
||||
/// pre- or post-state, never a torn one.
|
||||
///
|
||||
/// Closures passed to `read`/`mutate` run under the (non-recursive) lock
|
||||
/// and must not call back into the store.
|
||||
final class BLEPeerRegistryStore: @unchecked Sendable {
|
||||
private let lock = NSLock()
|
||||
private var registry = BLEPeerRegistry()
|
||||
|
||||
/// One consistent view across multiple registry reads.
|
||||
func read<T>(_ body: (BLEPeerRegistry) -> T) -> T {
|
||||
lock.withLock { body(registry) }
|
||||
}
|
||||
|
||||
func mutate<T>(_ body: (inout BLEPeerRegistry) -> T) -> T {
|
||||
lock.withLock { body(®istry) }
|
||||
}
|
||||
|
||||
// MARK: - Single-question reads
|
||||
|
||||
var isEmpty: Bool { read { $0.isEmpty } }
|
||||
var count: Int { read { $0.count } }
|
||||
var peerIDs: [PeerID] { read { $0.peerIDs } }
|
||||
var connectedCount: Int { read { $0.connectedCount } }
|
||||
var connectedPeerIDs: [PeerID] { read { $0.connectedPeerIDs } }
|
||||
var connectedRoutingData: [Data] { read { $0.connectedRoutingData } }
|
||||
var snapshotByID: [PeerID: BLEPeerInfo] { read { $0.snapshotByID } }
|
||||
|
||||
func info(for peerID: PeerID) -> BLEPeerInfo? {
|
||||
read { $0.info(for: peerID) }
|
||||
}
|
||||
|
||||
func isConnected(_ peerID: PeerID) -> Bool {
|
||||
read { $0.isConnected(peerID) }
|
||||
}
|
||||
|
||||
func isReachable(_ peerID: PeerID, now: Date) -> Bool {
|
||||
read { $0.isReachable(peerID, now: now) }
|
||||
}
|
||||
|
||||
func nickname(for peerID: PeerID, connectedOnly: Bool) -> String? {
|
||||
read { $0.nickname(for: peerID, connectedOnly: connectedOnly) }
|
||||
}
|
||||
|
||||
func fingerprint(for peerID: PeerID) -> String? {
|
||||
read { $0.fingerprint(for: peerID) }
|
||||
}
|
||||
|
||||
func capabilities(for peerID: PeerID) -> PeerCapabilities {
|
||||
read { $0.capabilities(for: peerID) }
|
||||
}
|
||||
|
||||
func capabilitiesWereExplicitlyAdvertised(for peerID: PeerID) -> Bool {
|
||||
read { $0.capabilitiesWereExplicitlyAdvertised(for: peerID) }
|
||||
}
|
||||
|
||||
func advertisedBridgeGeohash() -> String? {
|
||||
read { $0.advertisedBridgeGeohash() }
|
||||
}
|
||||
|
||||
func displayNicknames(selfNickname: String) -> [PeerID: String] {
|
||||
read { $0.displayNicknames(selfNickname: selfNickname) }
|
||||
}
|
||||
|
||||
func transportSnapshots(selfNickname: String) -> [TransportPeerSnapshot] {
|
||||
read { $0.transportSnapshots(selfNickname: selfNickname) }
|
||||
}
|
||||
|
||||
/// Peers advertising `capability` that are reachable now, in one
|
||||
/// consistent view.
|
||||
func reachablePeers(advertising capability: PeerCapabilities, now: Date) -> [PeerID] {
|
||||
read { registry in
|
||||
registry.peers(advertising: capability)
|
||||
.filter { registry.isReachable($0, now: now) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -77,6 +77,26 @@ struct BLEReceivePipeline {
|
||||
}
|
||||
}
|
||||
|
||||
/// Lock-backed traffic-level signal: the receive pipeline records packets,
|
||||
/// and the radio layer (maintenance and scan-duty adaptation on bleQueue)
|
||||
/// reads the level without crossing onto a transport queue.
|
||||
final class BLERecentTrafficMonitor: @unchecked Sendable {
|
||||
private let lock = NSLock()
|
||||
private var tracker = BLERecentTrafficTracker()
|
||||
|
||||
func recordPacket(at now: Date) {
|
||||
lock.withLock { tracker.recordPacket(at: now) }
|
||||
}
|
||||
|
||||
func hasTraffic(within seconds: TimeInterval, now: Date) -> Bool {
|
||||
lock.withLock { tracker.hasTraffic(within: seconds, now: now) }
|
||||
}
|
||||
|
||||
func removeAll() {
|
||||
lock.withLock { tracker.removeAll() }
|
||||
}
|
||||
}
|
||||
|
||||
struct BLERecentTrafficTracker: Equatable {
|
||||
private var packetTimestamps: [Date] = []
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -110,6 +110,10 @@ final class MessageOutboxStore {
|
||||
/// Delivery/read acknowledgments received before a deferred cold-load
|
||||
/// reveals the durable queue. Applied to every merge before persistence.
|
||||
private var pendingRemovalMessageIDs = Set<String>()
|
||||
/// Peer-scoped acknowledgments received before a deferred cold-load
|
||||
/// reveals the durable queue. Unlike the legacy global tombstones above,
|
||||
/// these must not remove a colliding message ID queued for another peer.
|
||||
private var pendingScopedRemovalMessageIDs: [PeerID: Set<String>] = [:]
|
||||
private var recoveryHandler: (@MainActor (Snapshot) -> Void)?
|
||||
/// Recovery loaded durable state that MessageRouter has not merged yet.
|
||||
/// While true, router saves must union with `cachedSnapshot` instead of
|
||||
@@ -195,7 +199,7 @@ final class MessageOutboxStore {
|
||||
? (pendingSnapshot ?? [:])
|
||||
: Self.merge(durable, pendingSnapshot ?? [:]))
|
||||
diskState = .loaded
|
||||
if pendingSnapshot != nil || !pendingRemovalMessageIDs.isEmpty {
|
||||
if pendingSnapshot != nil || hasPendingRemovalsLocked {
|
||||
if persistSnapshotAndClearRemovalsLocked(cachedSnapshot) {
|
||||
pendingSnapshot = nil
|
||||
pendingSnapshotIsAuthoritative = false
|
||||
@@ -212,7 +216,7 @@ final class MessageOutboxStore {
|
||||
case .missing:
|
||||
cachedSnapshot = applyingPendingRemovalsLocked(pendingSnapshot ?? [:])
|
||||
diskState = .loaded
|
||||
if pendingSnapshot != nil || !pendingRemovalMessageIDs.isEmpty {
|
||||
if pendingSnapshot != nil || hasPendingRemovalsLocked {
|
||||
if persistSnapshotAndClearRemovalsLocked(cachedSnapshot) {
|
||||
pendingSnapshot = nil
|
||||
pendingSnapshotIsAuthoritative = false
|
||||
@@ -235,7 +239,7 @@ final class MessageOutboxStore {
|
||||
diskState = .loaded
|
||||
cachedSnapshot = applyingPendingRemovalsLocked(pendingSnapshot ?? [:])
|
||||
SecureLogger.error("Failed to decode encrypted outbox: \(error)", category: .session)
|
||||
if pendingSnapshot != nil || !pendingRemovalMessageIDs.isEmpty {
|
||||
if pendingSnapshot != nil || hasPendingRemovalsLocked {
|
||||
if persistSnapshotAndClearRemovalsLocked(cachedSnapshot) {
|
||||
pendingSnapshot = nil
|
||||
pendingSnapshotIsAuthoritative = false
|
||||
@@ -442,6 +446,25 @@ final class MessageOutboxStore {
|
||||
lock.unlock()
|
||||
}
|
||||
|
||||
/// Records an ack for only the supplied peer aliases. This preserves
|
||||
/// another recipient's queued entry when message IDs happen to collide,
|
||||
/// including while the durable snapshot is hidden by protected data.
|
||||
func recordRemoval(messageID: String, for peerIDs: Set<PeerID>) {
|
||||
guard !peerIDs.isEmpty else { return }
|
||||
|
||||
lock.lock()
|
||||
for peerID in peerIDs {
|
||||
pendingScopedRemovalMessageIDs[peerID, default: []].insert(messageID)
|
||||
}
|
||||
cachedSnapshot = Self.removing(pendingScopedRemovalMessageIDs, from: cachedSnapshot)
|
||||
unseenRecoveredSnapshot = Self.removing(pendingScopedRemovalMessageIDs, from: unseenRecoveredSnapshot)
|
||||
recoveryRouterSnapshot = Self.removing(pendingScopedRemovalMessageIDs, from: recoveryRouterSnapshot)
|
||||
if let pendingSnapshot {
|
||||
self.pendingSnapshot = Self.removing(pendingScopedRemovalMessageIDs, from: pendingSnapshot)
|
||||
}
|
||||
lock.unlock()
|
||||
}
|
||||
|
||||
/// Retries a deferred protected-data load. The returned snapshot includes
|
||||
/// both durable messages and any messages queued during the locked wake.
|
||||
@discardableResult
|
||||
@@ -478,7 +501,7 @@ final class MessageOutboxStore {
|
||||
: (pendingSnapshotIsAuthoritative ? known : Self.merge(durable, known)))
|
||||
cachedSnapshot = merged
|
||||
diskState = .loaded
|
||||
if (pendingSnapshot == nil && pendingRemovalMessageIDs.isEmpty) ||
|
||||
if (pendingSnapshot == nil && !hasPendingRemovalsLocked) ||
|
||||
persistSnapshotAndClearRemovalsLocked(merged) {
|
||||
pendingSnapshot = nil
|
||||
pendingSnapshotIsAuthoritative = false
|
||||
@@ -507,7 +530,7 @@ final class MessageOutboxStore {
|
||||
: known)
|
||||
cachedSnapshot = merged
|
||||
diskState = .loaded
|
||||
if (pendingSnapshot == nil && pendingRemovalMessageIDs.isEmpty) ||
|
||||
if (pendingSnapshot == nil && !hasPendingRemovalsLocked) ||
|
||||
persistSnapshotAndClearRemovalsLocked(merged) {
|
||||
pendingSnapshot = nil
|
||||
pendingSnapshotIsAuthoritative = false
|
||||
@@ -539,7 +562,7 @@ final class MessageOutboxStore {
|
||||
: known)
|
||||
cachedSnapshot = merged
|
||||
diskState = .loaded
|
||||
if (pendingSnapshot == nil && pendingRemovalMessageIDs.isEmpty) ||
|
||||
if (pendingSnapshot == nil && !hasPendingRemovalsLocked) ||
|
||||
persistSnapshotAndClearRemovalsLocked(merged) {
|
||||
pendingSnapshot = nil
|
||||
pendingSnapshotIsAuthoritative = false
|
||||
@@ -578,6 +601,7 @@ final class MessageOutboxStore {
|
||||
pendingSnapshot = nil
|
||||
pendingSnapshotIsAuthoritative = false
|
||||
pendingRemovalMessageIDs.removeAll()
|
||||
pendingScopedRemovalMessageIDs.removeAll()
|
||||
recoveryDeliveryPending = false
|
||||
unseenRecoveryPendingPersistence = false
|
||||
unseenRecoveredSnapshot = [:]
|
||||
@@ -742,12 +766,21 @@ final class MessageOutboxStore {
|
||||
private func persistSnapshotAndClearRemovalsLocked(_ snapshot: Snapshot) -> Bool {
|
||||
guard persistSnapshotLocked(snapshot) else { return false }
|
||||
pendingRemovalMessageIDs.removeAll()
|
||||
pendingScopedRemovalMessageIDs.removeAll()
|
||||
return true
|
||||
}
|
||||
|
||||
/// Must be called with `lock` held.
|
||||
private func applyingPendingRemovalsLocked(_ snapshot: Snapshot) -> Snapshot {
|
||||
Self.removing(pendingRemovalMessageIDs, from: snapshot)
|
||||
Self.removing(
|
||||
pendingScopedRemovalMessageIDs,
|
||||
from: Self.removing(pendingRemovalMessageIDs, from: snapshot)
|
||||
)
|
||||
}
|
||||
|
||||
/// Must be read with `lock` held.
|
||||
private var hasPendingRemovalsLocked: Bool {
|
||||
!pendingRemovalMessageIDs.isEmpty || !pendingScopedRemovalMessageIDs.isEmpty
|
||||
}
|
||||
|
||||
private static func removing(_ messageIDs: Set<String>, from snapshot: Snapshot) -> Snapshot {
|
||||
@@ -760,9 +793,28 @@ final class MessageOutboxStore {
|
||||
return filtered
|
||||
}
|
||||
|
||||
private static func removing(
|
||||
_ messageIDsByPeer: [PeerID: Set<String>],
|
||||
from snapshot: Snapshot
|
||||
) -> Snapshot {
|
||||
guard !messageIDsByPeer.isEmpty else { return snapshot }
|
||||
var filtered = snapshot
|
||||
for (peerID, messageIDs) in messageIDsByPeer {
|
||||
guard !messageIDs.isEmpty, let queue = filtered[peerID] else { continue }
|
||||
let remaining = queue.filter { !messageIDs.contains($0.messageID) }
|
||||
filtered[peerID] = remaining.isEmpty ? nil : remaining
|
||||
}
|
||||
return filtered
|
||||
}
|
||||
|
||||
private static func excludingKnownMessages(from durable: Snapshot, known: Snapshot) -> Snapshot {
|
||||
let knownIDs = Set(known.values.flatMap { $0.map(\.messageID) })
|
||||
return removing(knownIDs, from: durable)
|
||||
var unseen: Snapshot = [:]
|
||||
for (peerID, durableQueue) in durable {
|
||||
let knownIDs = Set(known[peerID]?.map(\.messageID) ?? [])
|
||||
let remaining = durableQueue.filter { !knownIDs.contains($0.messageID) }
|
||||
if !remaining.isEmpty { unseen[peerID] = remaining }
|
||||
}
|
||||
return unseen
|
||||
}
|
||||
|
||||
private static func merge(_ durable: Snapshot, _ pending: Snapshot) -> Snapshot {
|
||||
|
||||
@@ -106,13 +106,14 @@ final class BridgeCourierService: ObservableObject {
|
||||
dedupKey: String?,
|
||||
operationID: UUID?
|
||||
)] = []
|
||||
/// Message IDs already published as drops (sender-side dedup) and drop
|
||||
/// event IDs already handled (multi-relay dedup). Both persist across
|
||||
/// relaunches: relays hold drops for the full 24h NIP-40 window and the
|
||||
/// persisted outbox keeps re-depositing, so in-memory-only dedup meant
|
||||
/// every relaunch republished the same message as a fresh drop and every
|
||||
/// gateway relaunch re-delivered the whole backlog (field-verified
|
||||
/// amplification storm). Entries age out with the 24h drop window.
|
||||
/// Opaque recipient/message keys already published as drops (sender-side
|
||||
/// dedup) and drop event IDs already handled (multi-relay dedup). Both
|
||||
/// persist across relaunches: relays hold drops for the full 24h NIP-40
|
||||
/// window and the persisted outbox keeps re-depositing, so in-memory-only
|
||||
/// dedup meant every relaunch republished the same message as a fresh drop
|
||||
/// and every gateway relaunch re-delivered the whole backlog
|
||||
/// (field-verified amplification storm). Entries age out with the 24h drop
|
||||
/// window.
|
||||
private var publishedDropKeys: ExpiringIDSet
|
||||
private var seenDropEventIDs: ExpiringIDSet
|
||||
private var subscriptionOpen = false
|
||||
@@ -126,7 +127,7 @@ final class BridgeCourierService: ObservableObject {
|
||||
}
|
||||
/// Sender operations queued locally or awaiting relay confirmation.
|
||||
/// The per-attempt ID prevents a stale pre-wipe callback from completing
|
||||
/// a newer attempt for the same message.
|
||||
/// a newer attempt for the same recipient/message pair.
|
||||
private var activeDropOperations: [String: ActiveDropOperation] = [:]
|
||||
/// Held-envelope publishes have no sender message ID, but still need an
|
||||
/// in-flight identity: repeated refreshes inside the relay-OK wait window
|
||||
@@ -214,11 +215,46 @@ final class BridgeCourierService: ObservableObject {
|
||||
|
||||
// MARK: - Sender role
|
||||
|
||||
/// Stable, opaque sender-side dedup key. Recipient scope prevents one
|
||||
/// conversation's colliding message ID from suppressing another's drop,
|
||||
/// while hashing keeps recipient keys out of the persisted snapshot.
|
||||
private static func senderDropKey(
|
||||
messageID: String,
|
||||
recipientNoiseKey: Data
|
||||
) -> String {
|
||||
var material = Data("bitchat-bridge-drop-dedup-v2".utf8)
|
||||
appendLengthPrefixed(Data(messageID.utf8), to: &material)
|
||||
appendLengthPrefixed(recipientNoiseKey, to: &material)
|
||||
return "v2:\(material.sha256Hex())"
|
||||
}
|
||||
|
||||
private static func appendLengthPrefixed(_ value: Data, to output: inout Data) {
|
||||
let length = UInt32(value.count)
|
||||
output.append(UInt8((length >> 24) & 0xFF))
|
||||
output.append(UInt8((length >> 16) & 0xFF))
|
||||
output.append(UInt8((length >> 8) & 0xFF))
|
||||
output.append(UInt8(length & 0xFF))
|
||||
output.append(value)
|
||||
}
|
||||
|
||||
/// Previous releases persisted raw message IDs without recipient scope.
|
||||
/// They remain conservative wildcards for their original 24-hour
|
||||
/// lifetime: assigning one to a recipient would be guesswork and could
|
||||
/// republish the original drop. New acceptances persist only v2 keys.
|
||||
private func wasPublished(
|
||||
legacyMessageID: String,
|
||||
dedupKey: String,
|
||||
now date: Date
|
||||
) -> Bool {
|
||||
publishedDropKeys.contains(dedupKey, now: date)
|
||||
|| publishedDropKeys.contains(legacyMessageID, now: date)
|
||||
}
|
||||
|
||||
/// Parallel-deposit a sealed copy of an outbound private message as a
|
||||
/// relay drop. Called by the message router alongside physical courier
|
||||
/// deposits; idempotent per message ID. Completion becomes true only
|
||||
/// after a real relay acceptance arrives, which is when the router may
|
||||
/// show "carried".
|
||||
/// deposits; idempotent per recipient/message pair. Completion becomes
|
||||
/// true only after a real relay acceptance arrives, which is when the
|
||||
/// router may show "carried".
|
||||
func depositDrop(
|
||||
content: String,
|
||||
messageID: String,
|
||||
@@ -229,9 +265,18 @@ final class BridgeCourierService: ObservableObject {
|
||||
completion(false)
|
||||
return
|
||||
}
|
||||
guard !publishedDropKeys.contains(messageID, now: now()),
|
||||
activeDropOperations[messageID] == nil,
|
||||
!rejectedDropKeys.contains(messageID, now: now()) else {
|
||||
let date = now()
|
||||
let dedupKey = Self.senderDropKey(
|
||||
messageID: messageID,
|
||||
recipientNoiseKey: recipientNoiseKey
|
||||
)
|
||||
guard !wasPublished(
|
||||
legacyMessageID: messageID,
|
||||
dedupKey: dedupKey,
|
||||
now: date
|
||||
),
|
||||
activeDropOperations[dedupKey] == nil,
|
||||
!rejectedDropKeys.contains(dedupKey, now: date) else {
|
||||
completion(false)
|
||||
return
|
||||
}
|
||||
@@ -244,13 +289,13 @@ final class BridgeCourierService: ObservableObject {
|
||||
// of the sealing); suppress it in-memory so the retry sweep does not
|
||||
// churn, but never persist it as a published drop.
|
||||
guard let encoded = envelope.encode(), encoded.count <= Limits.maxDropEnvelopeBytes else {
|
||||
rejectedDropKeys.insert(messageID, now: now())
|
||||
rejectedDropKeys.insert(dedupKey, now: date)
|
||||
completion(false)
|
||||
return
|
||||
}
|
||||
let operationID = UUID()
|
||||
activeDropOperations[messageID] = ActiveDropOperation(id: operationID, completion: completion)
|
||||
publishDrop(envelope, messageID: messageID, operationID: operationID)
|
||||
activeDropOperations[dedupKey] = ActiveDropOperation(id: operationID, completion: completion)
|
||||
publishDrop(envelope, dedupKey: dedupKey, operationID: operationID)
|
||||
}
|
||||
|
||||
/// Publishes held envelopes (mail we carry for others) as drops,
|
||||
@@ -272,13 +317,14 @@ final class BridgeCourierService: ObservableObject {
|
||||
}
|
||||
}
|
||||
|
||||
/// Publishes a drop, or queues it when relays are down. `messageID` is the
|
||||
/// sender-side dedup key (nil for held/relayed envelopes we don't track);
|
||||
/// it rides the pending queue so an evicted or failed drop can release its
|
||||
/// in-flight slot. Completion reports actual NIP-01 relay acceptance.
|
||||
/// Publishes a drop, or queues it when relays are down. `dedupKey` is the
|
||||
/// opaque sender-side recipient/message key (nil for held/relayed
|
||||
/// envelopes we don't track); it rides the pending queue so an evicted or
|
||||
/// failed drop can release its in-flight slot. Completion reports actual
|
||||
/// NIP-01 relay acceptance.
|
||||
private func publishDrop(
|
||||
_ envelope: CourierEnvelope,
|
||||
messageID: String? = nil,
|
||||
dedupKey: String? = nil,
|
||||
operationID: UUID? = nil,
|
||||
untrackedCompletion: (@MainActor (Bool) -> Void)? = nil
|
||||
) {
|
||||
@@ -286,7 +332,7 @@ final class BridgeCourierService: ObservableObject {
|
||||
encoded.count <= Limits.maxDropEnvelopeBytes,
|
||||
!envelope.isExpired else {
|
||||
finishPublish(
|
||||
messageID: messageID,
|
||||
dedupKey: dedupKey,
|
||||
operationID: operationID,
|
||||
succeeded: false,
|
||||
untrackedCompletion: untrackedCompletion
|
||||
@@ -297,15 +343,15 @@ final class BridgeCourierService: ObservableObject {
|
||||
// Held mail remains in CourierStore and has no sender operation to
|
||||
// recover after an in-memory queue loss. Leave its cooldown unset
|
||||
// and let the next connected refresh offer it again.
|
||||
guard messageID != nil else {
|
||||
guard dedupKey != nil else {
|
||||
untrackedCompletion?(false)
|
||||
return
|
||||
}
|
||||
pendingDrops.append((envelope, messageID, operationID))
|
||||
pendingDrops.append((envelope, dedupKey, operationID))
|
||||
while pendingDrops.count > Limits.maxPendingDrops {
|
||||
let evicted = pendingDrops.removeFirst()
|
||||
finishPublish(
|
||||
messageID: evicted.dedupKey,
|
||||
dedupKey: evicted.dedupKey,
|
||||
operationID: evicted.operationID,
|
||||
succeeded: false
|
||||
)
|
||||
@@ -321,7 +367,7 @@ final class BridgeCourierService: ObservableObject {
|
||||
) else {
|
||||
SecureLogger.error("📦🌉 Failed to compose courier drop", category: .encryption)
|
||||
finishPublish(
|
||||
messageID: messageID,
|
||||
dedupKey: dedupKey,
|
||||
operationID: operationID,
|
||||
succeeded: false,
|
||||
untrackedCompletion: untrackedCompletion
|
||||
@@ -331,7 +377,7 @@ final class BridgeCourierService: ObservableObject {
|
||||
guard let publishEvent else {
|
||||
SecureLogger.error("📦🌉 Courier drop publisher is not configured", category: .session)
|
||||
finishPublish(
|
||||
messageID: messageID,
|
||||
dedupKey: dedupKey,
|
||||
operationID: operationID,
|
||||
succeeded: false,
|
||||
untrackedCompletion: untrackedCompletion
|
||||
@@ -341,7 +387,7 @@ final class BridgeCourierService: ObservableObject {
|
||||
publishEvent(event) { [weak self] succeeded in
|
||||
guard let self else { return }
|
||||
guard self.finishPublish(
|
||||
messageID: messageID,
|
||||
dedupKey: dedupKey,
|
||||
operationID: operationID,
|
||||
succeeded: succeeded,
|
||||
untrackedCompletion: untrackedCompletion
|
||||
@@ -356,23 +402,23 @@ final class BridgeCourierService: ObservableObject {
|
||||
|
||||
@discardableResult
|
||||
private func finishPublish(
|
||||
messageID: String?,
|
||||
dedupKey: String?,
|
||||
operationID: UUID?,
|
||||
succeeded: Bool,
|
||||
untrackedCompletion: (@MainActor (Bool) -> Void)? = nil
|
||||
) -> Bool {
|
||||
guard let messageID else {
|
||||
guard let dedupKey else {
|
||||
untrackedCompletion?(succeeded)
|
||||
return true
|
||||
}
|
||||
// Missing/mismatched means this callback was duplicated, invalidated
|
||||
// by panic wipe, or belongs to an older attempt for the same key.
|
||||
guard let operationID,
|
||||
let operation = activeDropOperations[messageID],
|
||||
let operation = activeDropOperations[dedupKey],
|
||||
operation.id == operationID else { return false }
|
||||
activeDropOperations.removeValue(forKey: messageID)
|
||||
activeDropOperations.removeValue(forKey: dedupKey)
|
||||
if succeeded {
|
||||
publishedDropKeys.insert(messageID, now: now())
|
||||
publishedDropKeys.insert(dedupKey, now: now())
|
||||
persistDedup()
|
||||
}
|
||||
operation.completion(succeeded)
|
||||
@@ -387,7 +433,7 @@ final class BridgeCourierService: ObservableObject {
|
||||
for item in queued {
|
||||
publishDrop(
|
||||
item.envelope,
|
||||
messageID: item.dedupKey,
|
||||
dedupKey: item.dedupKey,
|
||||
operationID: item.operationID
|
||||
)
|
||||
}
|
||||
|
||||
@@ -64,11 +64,11 @@ struct ExpiringIDSet {
|
||||
/// fresh drop (fresh throwaway seal, undeduplicatable downstream) and every
|
||||
/// gateway relaunch re-delivered the whole backlog. Field-verified: ~20
|
||||
/// copies of one DM delivered in 40ms fed the storm behind a permanent
|
||||
/// device freeze. Persisting both sides caps this at one drop per message
|
||||
/// ID per 24h regardless of relaunch count.
|
||||
/// device freeze. Persisting both sides caps this at one drop per
|
||||
/// recipient/message pair per 24h regardless of relaunch count.
|
||||
///
|
||||
/// Contents are opaque IDs (message UUIDs, relay event IDs) — no plaintext,
|
||||
/// no peer identities — so until-first-unlock protection matches
|
||||
/// Contents are opaque hashes and relay event IDs — no plaintext or peer
|
||||
/// identities — so until-first-unlock protection matches
|
||||
/// `NostrProcessedEventStore`, and the file must load during a
|
||||
/// locked-background restoration relaunch. Wiped on panic with the rest of
|
||||
/// the courier state.
|
||||
|
||||
@@ -10,9 +10,12 @@ import Foundation
|
||||
|
||||
/// Watermark for "heard here earlier" echoes: clearing the mesh timeline
|
||||
/// (triple-tap or /clear) records the moment, and the next launch only
|
||||
/// re-seeds archived messages heard after it. The archive itself is left
|
||||
/// alone — the device keeps carrying those messages for peers; the user
|
||||
/// just doesn't want to see them again.
|
||||
/// re-seeds archived messages heard after it.
|
||||
///
|
||||
/// Clearing also erases the archive itself, so cleared history is gone from
|
||||
/// disk rather than merely hidden from the timeline. The watermark still
|
||||
/// matters afterwards: it keeps messages this device hears again from peers,
|
||||
/// which predate the clear, from reappearing as echoes.
|
||||
enum MeshEchoSettings {
|
||||
private static let clearedThroughKey = "meshEchoes.clearedThrough"
|
||||
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import BitFoundation
|
||||
import CoreBluetooth
|
||||
import Foundation
|
||||
|
||||
/// Optional transport capabilities, discovered with `as?` instead of casting
|
||||
/// to a concrete transport class. `Transport` stays the contract every
|
||||
/// transport genuinely implements; a capability protocol here is the
|
||||
/// contract for one mesh-only feature surface, so app wiring depends on the
|
||||
/// feature it needs rather than on `BLEService` itself.
|
||||
|
||||
/// Radio-state reporting for transports backed by a local radio.
|
||||
protocol BluetoothStateReporting: AnyObject {
|
||||
func getCurrentBluetoothState() -> CBManagerState
|
||||
}
|
||||
|
||||
/// Panic-mode lifecycle for transports that own durable identity state.
|
||||
/// A transport implementing this owns its own restart sequencing:
|
||||
/// `completePanicReset` decides whether services come back, so generic
|
||||
/// `startServices()` calls after a panic belong only to transports that
|
||||
/// don't implement it.
|
||||
protocol PanicResettingTransport: AnyObject {
|
||||
/// Quiesces the radio and drains in-flight work ahead of a panic wipe.
|
||||
func suspendForPanicReset()
|
||||
/// Finishes a panic wipe, optionally restarting services.
|
||||
func completePanicReset(restartServices: Bool)
|
||||
/// Rotates the transport identity as part of a panic reset.
|
||||
func resetIdentityForPanic(currentNickname: String, restartServices: Bool)
|
||||
}
|
||||
|
||||
/// Internet-gateway and geohash-bridge wiring surface (BLE mesh today).
|
||||
/// Everything the gateway/bridge/courier services need from the mesh
|
||||
/// transport, so their bootstrap wiring never touches the concrete class.
|
||||
protocol MeshBridgingTransport: AnyObject {
|
||||
// Runtime-advertised capability bits
|
||||
func setLocalCapability(_ capability: PeerCapabilities, enabled: Bool)
|
||||
func setLocalBridgeGeohash(_ cell: String?)
|
||||
func advertisedBridgeGeohash() -> String?
|
||||
|
||||
// Peers currently advertising bridging roles
|
||||
func reachableGatewayPeers() -> [PeerID]
|
||||
func reachableBridgePeers() -> [PeerID]
|
||||
|
||||
// Gateway carrier packets (mesh <-> Nostr uplink/downlink)
|
||||
@discardableResult
|
||||
func sendNostrCarrier(_ payload: Data, to gatewayPeer: PeerID) -> Bool
|
||||
func broadcastNostrCarrier(_ payload: Data)
|
||||
/// Sink for received carrier packets (set once by app wiring; called on
|
||||
/// the main actor after transport-level checks).
|
||||
var onNostrCarrierPacket: (@MainActor (_ payload: Data, _ from: PeerID, _ directedToUs: Bool) -> Void)? { get set }
|
||||
|
||||
// Bridge courier drops (sealed envelopes carried across the bridge)
|
||||
func sealBridgeCourierEnvelope(_ content: String, messageID: String, recipientNoiseKey: Data) -> CourierEnvelope?
|
||||
@discardableResult
|
||||
func openBridgedCourierEnvelope(_ envelope: CourierEnvelope) -> Bool
|
||||
@discardableResult
|
||||
func deliverBridgedEnvelope(_ envelope: CourierEnvelope, to peerID: PeerID) -> Bool
|
||||
func myNoiseStaticPublicKey() -> Data
|
||||
func verifiedPeersWithNoiseKeys() -> [(peerID: PeerID, noiseKey: Data)]
|
||||
/// Fired (off-main) when a signature-verified announce is processed.
|
||||
var onVerifiedPeerAnnounce: ((_ peerID: PeerID) -> Void)? { get set }
|
||||
}
|
||||
@@ -34,6 +34,15 @@ struct CourierDirectory {
|
||||
final class MessageRouter {
|
||||
typealias QueuedMessage = MessageOutboxStore.QueuedMessage
|
||||
|
||||
private struct PeerMessageKey: Hashable {
|
||||
// periphery:ignore - read only via the synthesized Hashable
|
||||
// conformance (dictionary-key identity), which the indexer
|
||||
// cannot attribute; see retain_codable_properties in .periphery.yml
|
||||
// for the same class of false positive.
|
||||
let peerID: PeerID
|
||||
let messageID: String
|
||||
}
|
||||
|
||||
private let transports: [Transport]
|
||||
private let now: () -> Date
|
||||
private let courierDirectory: CourierDirectory
|
||||
@@ -104,15 +113,25 @@ final class MessageRouter {
|
||||
}
|
||||
|
||||
private var bridgeSweepTask: Task<Void, Never>?
|
||||
private var bridgeDepositsInFlight = Set<String>()
|
||||
private var bridgeDepositsInFlight = Set<PeerMessageKey>()
|
||||
|
||||
private var outbox: [PeerID: [QueuedMessage]] = [:]
|
||||
/// Peer/message pairs whose latest router-owned transmission used an
|
||||
/// already-established secure session and still await an ack. Peer scope
|
||||
/// is required because message IDs are not globally unique across direct
|
||||
/// conversations. This deliberately excludes messages handed to BLE while
|
||||
/// a handshake is pending: BLE owns those sends and drains its queue after
|
||||
/// authentication, so retrying them here would duplicate every normal
|
||||
/// first-handshake DM.
|
||||
private var secureTransmissions = Set<PeerMessageKey>()
|
||||
|
||||
// Outbox limits to prevent unbounded memory growth
|
||||
private static let maxMessagesPerPeer = 100
|
||||
private static let messageTTLSeconds: TimeInterval = 24 * 60 * 60 // 24 hours
|
||||
// Bound resends of messages sent on a weak reachability signal that never
|
||||
// get a delivery ack (e.g. peer on an old client that doesn't ack).
|
||||
// Bound actual sends that never receive an ack, whether they used weak
|
||||
// reachability or an apparently secure session that keeps being replaced.
|
||||
// Connected pre-handshake sends are transport-owned and do not burn this
|
||||
// cap because BLE queues/drains them itself.
|
||||
private static let maxSendAttempts = 8
|
||||
// Redundant couriers improve delivery odds; receivers dedup by message ID.
|
||||
private static let maxCouriersPerMessage = 3
|
||||
@@ -171,15 +190,28 @@ final class MessageRouter {
|
||||
// MARK: - Message Sending
|
||||
|
||||
func sendPrivate(_ content: String, to peerID: PeerID, recipientNickname: String, messageID: String) {
|
||||
let message = QueuedMessage(
|
||||
content: content,
|
||||
nickname: recipientNickname,
|
||||
messageID: messageID,
|
||||
timestamp: now(),
|
||||
sendAttempts: 1
|
||||
)
|
||||
|
||||
if let transport = connectedTransport(for: peerID), transport.canDeliverSecurely(to: peerID) {
|
||||
// A live link that can complete an encrypted delivery is a
|
||||
// strong delivery signal; trust it outright.
|
||||
// Even an established Noise session can be stale after the peer
|
||||
// restarts or replaces its app. Persist before handing the packet
|
||||
// to the transport so a fast ack cannot race ahead of retention,
|
||||
// then keep the copy until a delivery/read ack clears it. A
|
||||
// replacement handshake will retry this same message ID, which
|
||||
// receivers deduplicate.
|
||||
enqueue(message, for: peerID)
|
||||
secureTransmissions.insert(PeerMessageKey(peerID: peerID, messageID: messageID))
|
||||
SecureLogger.debug("Routing PM via \(type(of: transport)) (connected) to \(peerID.id.prefix(8))… id=\(messageID.prefix(8))…", category: .session)
|
||||
transport.sendPrivateMessage(content, to: peerID, recipientNickname: recipientNickname, messageID: messageID)
|
||||
return
|
||||
}
|
||||
|
||||
let message = QueuedMessage(content: content, nickname: recipientNickname, messageID: messageID, timestamp: now(), sendAttempts: 1)
|
||||
if let transport = connectedTransport(for: peerID) {
|
||||
// "Connected" without an established secure session is forgeable:
|
||||
// link bindings heal on signature-verified "direct" announces, but
|
||||
@@ -197,8 +229,9 @@ final class MessageRouter {
|
||||
// deposit is cleared on ack. Don't "optimize" the courier call
|
||||
// away.
|
||||
SecureLogger.debug("Routing PM via \(type(of: transport)) (connected, no secure session) to \(peerID.id.prefix(8))… id=\(messageID.prefix(8))…", category: .session)
|
||||
transport.sendPrivateMessage(content, to: peerID, recipientNickname: recipientNickname, messageID: messageID)
|
||||
enqueue(message, for: peerID)
|
||||
secureTransmissions.remove(PeerMessageKey(peerID: peerID, messageID: messageID))
|
||||
transport.sendPrivateMessage(content, to: peerID, recipientNickname: recipientNickname, messageID: messageID)
|
||||
attemptCourierDeposit(messageID: messageID, for: peerID)
|
||||
return
|
||||
}
|
||||
@@ -209,8 +242,8 @@ final class MessageRouter {
|
||||
// Send now, but retain a copy until a delivery/read ack clears it;
|
||||
// receivers dedup resends by message ID.
|
||||
SecureLogger.debug("Routing PM via \(type(of: transport)) (reachable) to \(peerID.id.prefix(8))… id=\(messageID.prefix(8))…", category: .session)
|
||||
transport.sendPrivateMessage(content, to: peerID, recipientNickname: recipientNickname, messageID: messageID)
|
||||
enqueue(message, for: peerID)
|
||||
transport.sendPrivateMessage(content, to: peerID, recipientNickname: recipientNickname, messageID: messageID)
|
||||
// "Reachable" without prompt delivery means the send only joined
|
||||
// a queue (Nostr with relays down): also hand a sealed copy to
|
||||
// any connected couriers rather than waiting for internet that
|
||||
@@ -333,11 +366,12 @@ final class MessageRouter {
|
||||
for peerID: PeerID,
|
||||
recipientKey: Data
|
||||
) {
|
||||
let inFlightKey = PeerMessageKey(peerID: peerID, messageID: message.messageID)
|
||||
guard let bridgeCourierDeposit,
|
||||
bridgeDepositsInFlight.insert(message.messageID).inserted else { return }
|
||||
bridgeDepositsInFlight.insert(inFlightKey).inserted else { return }
|
||||
bridgeCourierDeposit(message.content, message.messageID, recipientKey) { [weak self] succeeded in
|
||||
guard let self else { return }
|
||||
self.bridgeDepositsInFlight.remove(message.messageID)
|
||||
self.bridgeDepositsInFlight.remove(inFlightKey)
|
||||
// A direct delivery may have cleared the outbox while the relay
|
||||
// relay confirmation was in flight; do not regress its UI state.
|
||||
guard succeeded, self.queuedMessage(message.messageID, for: peerID) != nil else { return }
|
||||
@@ -356,8 +390,23 @@ final class MessageRouter {
|
||||
|
||||
// MARK: - Outbox Management
|
||||
|
||||
/// A delivery or read ack confirms receipt; stop retaining the message.
|
||||
/// A locally trusted delivery transition confirms receipt; stop retaining
|
||||
/// every copy of the message. Authenticated remote receipts must use the
|
||||
/// peer-bound overload below instead.
|
||||
func markDelivered(_ messageID: String) {
|
||||
clearRetainedMessage(messageID)
|
||||
}
|
||||
|
||||
/// Stops retaining a message only for the authenticated conversation
|
||||
/// aliases that produced the accepted receipt. A peer that learns another
|
||||
/// conversation's message ID cannot use it to clear that conversation's
|
||||
/// retry state.
|
||||
func markDelivered(_ messageID: String, from peerIDs: Set<PeerID>) {
|
||||
guard !peerIDs.isEmpty else { return }
|
||||
_ = markDelivered(messageID, for: Array(peerIDs))
|
||||
}
|
||||
|
||||
private func clearRetainedMessage(_ messageID: String) {
|
||||
var cleared = false
|
||||
for (peerID, queue) in outbox {
|
||||
let filtered = queue.filter { $0.messageID != messageID }
|
||||
@@ -365,6 +414,10 @@ final class MessageRouter {
|
||||
outbox[peerID] = filtered.isEmpty ? nil : filtered
|
||||
cleared = true
|
||||
}
|
||||
let matchingSecureTransmissions = secureTransmissions.filter {
|
||||
$0.messageID == messageID
|
||||
}
|
||||
secureTransmissions.subtract(matchingSecureTransmissions)
|
||||
// The durable snapshot may still be hidden by protected data. Record
|
||||
// the ack even when this cold-load view cannot find the message, then
|
||||
// persist the current view so the store retains a removal tombstone.
|
||||
@@ -375,6 +428,35 @@ final class MessageRouter {
|
||||
persistOutbox()
|
||||
}
|
||||
|
||||
/// A delivery or read ack authenticated to one account confirms receipt
|
||||
/// only for that account's transport aliases. A colliding message ID
|
||||
/// queued for another peer must remain retained.
|
||||
@discardableResult
|
||||
func markDelivered(_ messageID: String, for peerAliases: [PeerID]) -> Bool {
|
||||
let peerIDs = Set(peerAliases)
|
||||
guard !peerIDs.isEmpty else { return false }
|
||||
|
||||
var cleared = false
|
||||
for peerID in peerIDs {
|
||||
guard let queue = outbox[peerID] else { continue }
|
||||
let filtered = queue.filter { $0.messageID != messageID }
|
||||
guard filtered.count != queue.count else { continue }
|
||||
outbox[peerID] = filtered.isEmpty ? nil : filtered
|
||||
cleared = true
|
||||
}
|
||||
for peerID in peerIDs {
|
||||
secureTransmissions.remove(PeerMessageKey(peerID: peerID, messageID: messageID))
|
||||
}
|
||||
// Preserve the scoped ack even when protected data hides the durable
|
||||
// queue during a cold launch.
|
||||
outboxStore?.recordRemoval(messageID: messageID, for: peerIDs)
|
||||
if cleared {
|
||||
metrics?.record(.outboxDelivered)
|
||||
}
|
||||
persistOutbox()
|
||||
return cleared
|
||||
}
|
||||
|
||||
private func enqueue(_ message: QueuedMessage, for peerID: PeerID) {
|
||||
var message = message
|
||||
var queue = outbox[peerID] ?? []
|
||||
@@ -398,7 +480,34 @@ final class MessageRouter {
|
||||
persistOutbox()
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
private func removeQueuedMessage(_ messageID: String, for peerID: PeerID) -> Bool {
|
||||
guard let queue = outbox[peerID],
|
||||
let index = queue.firstIndex(where: { $0.messageID == messageID }) else {
|
||||
return false
|
||||
}
|
||||
var updated = queue
|
||||
updated.remove(at: index)
|
||||
outbox[peerID] = updated.isEmpty ? nil : updated
|
||||
return true
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
private func incrementSendAttemptsIfQueued(_ messageID: String, for peerID: PeerID) -> Bool {
|
||||
guard var queue = outbox[peerID],
|
||||
let index = queue.firstIndex(where: { $0.messageID == messageID }) else {
|
||||
// A synchronous delivery/read ack may have cleared the retained
|
||||
// copy while `sendPrivateMessage` was on the stack. Never
|
||||
// resurrect it from the flush snapshot.
|
||||
return false
|
||||
}
|
||||
queue[index].sendAttempts += 1
|
||||
outbox[peerID] = queue
|
||||
return true
|
||||
}
|
||||
|
||||
private func dropMessage(_ messageID: String, for peerID: PeerID) {
|
||||
secureTransmissions.remove(PeerMessageKey(peerID: peerID, messageID: messageID))
|
||||
metrics?.record(.outboxDropped)
|
||||
onMessageDropped?(messageID, peerID)
|
||||
}
|
||||
@@ -442,6 +551,7 @@ final class MessageRouter {
|
||||
/// Panic wipe: forget queued mail on disk and in memory.
|
||||
func wipeOutbox() {
|
||||
outbox.removeAll()
|
||||
secureTransmissions.removeAll()
|
||||
outboxStore?.wipe()
|
||||
}
|
||||
|
||||
@@ -469,26 +579,160 @@ final class MessageRouter {
|
||||
}
|
||||
}
|
||||
|
||||
/// Retries only messages that the router previously transmitted through
|
||||
/// an already-established secure session and that still await an ack.
|
||||
///
|
||||
/// A peer restart can leave that local session looking usable until the
|
||||
/// replacement handshake arrives; the first ciphertext is then
|
||||
/// undecryptable remotely. Normal pre-handshake sends are intentionally
|
||||
/// absent from `secureTransmissions` because BLE already queues
|
||||
/// and drains them when authentication completes.
|
||||
func retrySecurePrivateMessagesAfterAuthentication(for peerIDAliases: [PeerID]) {
|
||||
typealias Candidate = (
|
||||
peerID: PeerID,
|
||||
message: QueuedMessage,
|
||||
aliasOrder: Int,
|
||||
queueOrder: Int
|
||||
)
|
||||
|
||||
var visitedPeerIDs = Set<PeerID>()
|
||||
var retriedMessageIDs = Set<String>()
|
||||
var outboxChanged = false
|
||||
let currentDate = now()
|
||||
var candidates: [Candidate] = []
|
||||
|
||||
for (aliasOrder, peerID) in peerIDAliases.enumerated() {
|
||||
guard visitedPeerIDs.insert(peerID).inserted else { continue }
|
||||
guard let queued = outbox[peerID], !queued.isEmpty,
|
||||
let transport = connectedTransport(for: peerID),
|
||||
transport.canDeliverSecurely(to: peerID) else {
|
||||
continue
|
||||
}
|
||||
|
||||
for (queueOrder, message) in queued.enumerated() {
|
||||
let key = PeerMessageKey(peerID: peerID, messageID: message.messageID)
|
||||
guard secureTransmissions.contains(key) else { continue }
|
||||
candidates.append((
|
||||
peerID: peerID,
|
||||
message: message,
|
||||
aliasOrder: aliasOrder,
|
||||
queueOrder: queueOrder
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
// Conversation migration can leave retained messages split across the
|
||||
// ephemeral and stable outbox keys. Merge both queues into one
|
||||
// chronological stream so callback alias order cannot send newer mail
|
||||
// ahead of older mail.
|
||||
candidates.sort { lhs, rhs in
|
||||
if lhs.message.timestamp != rhs.message.timestamp {
|
||||
return lhs.message.timestamp < rhs.message.timestamp
|
||||
}
|
||||
if lhs.aliasOrder != rhs.aliasOrder {
|
||||
return lhs.aliasOrder < rhs.aliasOrder
|
||||
}
|
||||
if lhs.queueOrder != rhs.queueOrder {
|
||||
return lhs.queueOrder < rhs.queueOrder
|
||||
}
|
||||
return lhs.message.messageID < rhs.message.messageID
|
||||
}
|
||||
|
||||
for candidate in candidates {
|
||||
let peerID = candidate.peerID
|
||||
let message = candidate.message
|
||||
let key = PeerMessageKey(peerID: peerID, messageID: message.messageID)
|
||||
guard retriedMessageIDs.insert(message.messageID).inserted,
|
||||
secureTransmissions.contains(key),
|
||||
queuedMessage(message.messageID, for: peerID) != nil,
|
||||
let transport = connectedTransport(for: peerID),
|
||||
transport.canDeliverSecurely(to: peerID) else {
|
||||
continue
|
||||
}
|
||||
|
||||
if currentDate.timeIntervalSince(message.timestamp) > Self.messageTTLSeconds {
|
||||
if removeQueuedMessage(message.messageID, for: peerID) {
|
||||
dropMessage(message.messageID, for: peerID)
|
||||
outboxChanged = true
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
guard message.sendAttempts < Self.maxSendAttempts else {
|
||||
SecureLogger.warning(
|
||||
"📤 Dropping unacked PM for \(peerID.id.prefix(8))… id=\(message.messageID.prefix(8))… after \(message.sendAttempts) secure attempts",
|
||||
category: .session
|
||||
)
|
||||
if removeQueuedMessage(message.messageID, for: peerID) {
|
||||
dropMessage(message.messageID, for: peerID)
|
||||
outboxChanged = true
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
SecureLogger.debug(
|
||||
"Auth retry -> \(type(of: transport)) for \(peerID.id.prefix(8))… id=\(message.messageID.prefix(8))…",
|
||||
category: .session
|
||||
)
|
||||
transport.sendPrivateMessage(
|
||||
message.content,
|
||||
to: peerID,
|
||||
recipientNickname: message.nickname,
|
||||
messageID: message.messageID
|
||||
)
|
||||
metrics?.record(.outboxResent)
|
||||
outboxChanged = incrementSendAttemptsIfQueued(message.messageID, for: peerID) || outboxChanged
|
||||
}
|
||||
|
||||
if outboxChanged {
|
||||
persistOutbox()
|
||||
}
|
||||
}
|
||||
|
||||
func flushOutbox(for peerID: PeerID) {
|
||||
guard let queued = outbox[peerID], !queued.isEmpty else { return }
|
||||
SecureLogger.debug("Flushing outbox for \(peerID.id.prefix(8))… count=\(queued.count)", category: .session)
|
||||
|
||||
let now = now()
|
||||
var remaining: [QueuedMessage] = []
|
||||
var outboxChanged = false
|
||||
|
||||
for message in queued {
|
||||
// A synchronous ack from an earlier send in this flush may have
|
||||
// removed an entry from the live outbox. The snapshot is only an
|
||||
// iteration order; never use it to recreate removed messages.
|
||||
guard queuedMessage(message.messageID, for: peerID) != nil else { continue }
|
||||
|
||||
// Skip expired messages (TTL exceeded)
|
||||
if now.timeIntervalSince(message.timestamp) > Self.messageTTLSeconds {
|
||||
SecureLogger.debug("⏰ Expired queued message for \(peerID.id.prefix(8))… id=\(message.messageID.prefix(8))… (age: \(Int(now.timeIntervalSince(message.timestamp)))s)", category: .session)
|
||||
dropMessage(message.messageID, for: peerID)
|
||||
if removeQueuedMessage(message.messageID, for: peerID) {
|
||||
dropMessage(message.messageID, for: peerID)
|
||||
outboxChanged = true
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
if let transport = connectedTransport(for: peerID), transport.canDeliverSecurely(to: peerID) {
|
||||
// Live link with a secure session: send and stop retaining.
|
||||
// A secure session is meaningful enough to retry, but not
|
||||
// proof that this particular ciphertext reached the peer: the
|
||||
// remote app may have restarted while our old session still
|
||||
// looked established. Retain until an ack, while bounding
|
||||
// actual secure transmissions for peers that never ack.
|
||||
guard message.sendAttempts < Self.maxSendAttempts else {
|
||||
SecureLogger.warning("📤 Dropping unacked PM for \(peerID.id.prefix(8))… id=\(message.messageID.prefix(8))… after \(message.sendAttempts) attempts", category: .session)
|
||||
if removeQueuedMessage(message.messageID, for: peerID) {
|
||||
dropMessage(message.messageID, for: peerID)
|
||||
outboxChanged = true
|
||||
}
|
||||
continue
|
||||
}
|
||||
SecureLogger.debug("Outbox -> \(type(of: transport)) (connected) for \(peerID.id.prefix(8))… id=\(message.messageID.prefix(8))…", category: .session)
|
||||
secureTransmissions.insert(
|
||||
PeerMessageKey(peerID: peerID, messageID: message.messageID)
|
||||
)
|
||||
transport.sendPrivateMessage(message.content, to: peerID, recipientNickname: message.nickname, messageID: message.messageID)
|
||||
metrics?.record(.outboxResent)
|
||||
outboxChanged = incrementSendAttemptsIfQueued(message.messageID, for: peerID) || outboxChanged
|
||||
} else if let transport = connectedTransport(for: peerID) {
|
||||
// "Connected" without a secure session — possibly a stolen
|
||||
// binding from a replayed announce: send (a genuine link
|
||||
@@ -501,9 +745,11 @@ final class MessageRouter {
|
||||
// preserve. Retention stays bounded by the 24h outbox TTL
|
||||
// and the per-peer FIFO cap.
|
||||
SecureLogger.debug("Outbox -> \(type(of: transport)) (connected, no secure session) for \(peerID.id.prefix(8))… id=\(message.messageID.prefix(8))…", category: .session)
|
||||
secureTransmissions.remove(
|
||||
PeerMessageKey(peerID: peerID, messageID: message.messageID)
|
||||
)
|
||||
transport.sendPrivateMessage(message.content, to: peerID, recipientNickname: message.nickname, messageID: message.messageID)
|
||||
metrics?.record(.outboxResent)
|
||||
remaining.append(message)
|
||||
} else if let transport = reachableTransport(for: peerID) {
|
||||
// Reachability without a connection is a freshness heuristic,
|
||||
// so the send can silently go nowhere: send but keep retaining
|
||||
@@ -511,26 +757,22 @@ final class MessageRouter {
|
||||
// that never ack.
|
||||
guard message.sendAttempts < Self.maxSendAttempts else {
|
||||
SecureLogger.warning("📤 Dropping unacked PM for \(peerID.id.prefix(8))… id=\(message.messageID.prefix(8))… after \(message.sendAttempts) attempts", category: .session)
|
||||
dropMessage(message.messageID, for: peerID)
|
||||
if removeQueuedMessage(message.messageID, for: peerID) {
|
||||
dropMessage(message.messageID, for: peerID)
|
||||
outboxChanged = true
|
||||
}
|
||||
continue
|
||||
}
|
||||
SecureLogger.debug("Outbox -> \(type(of: transport)) (reachable) for \(peerID.id.prefix(8))… id=\(message.messageID.prefix(8))…", category: .session)
|
||||
transport.sendPrivateMessage(message.content, to: peerID, recipientNickname: message.nickname, messageID: message.messageID)
|
||||
metrics?.record(.outboxResent)
|
||||
var retained = message
|
||||
retained.sendAttempts += 1
|
||||
remaining.append(retained)
|
||||
} else {
|
||||
remaining.append(message)
|
||||
outboxChanged = incrementSendAttemptsIfQueued(message.messageID, for: peerID) || outboxChanged
|
||||
}
|
||||
}
|
||||
|
||||
if remaining.isEmpty {
|
||||
outbox.removeValue(forKey: peerID)
|
||||
} else {
|
||||
outbox[peerID] = remaining
|
||||
if outboxChanged {
|
||||
persistOutbox()
|
||||
}
|
||||
persistOutbox()
|
||||
}
|
||||
|
||||
func flushAllOutbox() {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -97,7 +97,7 @@ enum EncryptionStatus: Equatable {
|
||||
case noiseHandshaking // Currently establishing
|
||||
case noiseSecured // Established but not verified
|
||||
case noiseVerified // Established and verified
|
||||
|
||||
|
||||
var icon: String? { // Made optional to hide icon when no handshake
|
||||
switch self {
|
||||
case .none:
|
||||
@@ -663,7 +663,7 @@ final class NoiseEncryptionService {
|
||||
guard let packetData = packet.toBinaryDataForSigning() else {
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
// Sign with the noise private key (converted to Ed25519 for signing)
|
||||
guard let signature = signData(packetData) else {
|
||||
return nil
|
||||
@@ -922,7 +922,7 @@ final class NoiseEncryptionService {
|
||||
}
|
||||
return try sessionManager.encrypt(data, for: peerID)
|
||||
}
|
||||
|
||||
|
||||
/// Decrypt data from a specific peer
|
||||
func decrypt(_ data: Data, from peerID: PeerID) throws -> Data {
|
||||
try decryptWithSessionGeneration(data, from: peerID).plaintext
|
||||
@@ -939,7 +939,7 @@ final class NoiseEncryptionService {
|
||||
let isStandardCiphertext = NoiseSecurityValidator.validateCiphertextSize(data)
|
||||
let isAdmittedCiphertext = isStandardCiphertext
|
||||
|| NoiseSecurityValidator.validatePrivateFileCiphertextSize(data)
|
||||
|
||||
|
||||
// A quarantined transport is deliberately unavailable for outbound
|
||||
// state, but remains receive-only until the responder proves identity
|
||||
// or the bounded rollback restores it.
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
//
|
||||
// NotificationPrivacySettings.swift
|
||||
// bitchat
|
||||
//
|
||||
// This is free and unencumbered software released into the public domain.
|
||||
// For more information, see <https://unlicense.org>
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Controls how much a delivered notification says while the device is locked.
|
||||
///
|
||||
/// Notification content is rendered by the system on the lock screen, so it is
|
||||
/// readable by anyone holding the phone without unlocking it. With previews
|
||||
/// hidden, alerts still say that something arrived and stay tappable, but the
|
||||
/// message body, the sender's nickname, and the geohash are withheld until the
|
||||
/// app is opened.
|
||||
///
|
||||
/// Defaults to hidden: a locked phone lying on a table or taken at a protest
|
||||
/// should not narrate conversations, and someone who wants previews can say so.
|
||||
enum NotificationPrivacySettings {
|
||||
private static let hidePreviewsKey = "notifications.hideMessagePreviews"
|
||||
|
||||
static var hideMessagePreviews: Bool {
|
||||
get { hideMessagePreviews(in: .standard) }
|
||||
set { setHideMessagePreviews(newValue, in: .standard) }
|
||||
}
|
||||
|
||||
/// Store-injecting forms, so tests can assert the default and both settings
|
||||
/// without touching the shared preferences other tests read.
|
||||
static func hideMessagePreviews(in defaults: UserDefaults) -> Bool {
|
||||
defaults.object(forKey: hidePreviewsKey) as? Bool ?? true
|
||||
}
|
||||
|
||||
static func setHideMessagePreviews(_ hide: Bool, in defaults: UserDefaults) {
|
||||
defaults.set(hide, forKey: hidePreviewsKey)
|
||||
}
|
||||
|
||||
/// Panic-wipe hook. Removing the key restores the hidden default, so a
|
||||
/// wiped device cannot come back louder than a fresh install.
|
||||
static func reset(in defaults: UserDefaults = .standard) {
|
||||
defaults.removeObject(forKey: hidePreviewsKey)
|
||||
}
|
||||
}
|
||||
@@ -95,6 +95,35 @@ final class NotificationService {
|
||||
static let nearbyCategoryID = "chat.bitchat.category.nearby"
|
||||
static let waveActionID = "chat.bitchat.action.wave"
|
||||
|
||||
/// Copy used when `NotificationPrivacySettings.hideMessagePreviews` is on.
|
||||
/// These say that something arrived without naming who sent it, quoting it,
|
||||
/// or disclosing which geohash it came from.
|
||||
private enum Redacted {
|
||||
static var directMessageTitle: String {
|
||||
String(localized: "notification.redacted.dm.title", defaultValue: "🔒 new dm", comment: "Lock-screen notification title for a received direct message when message previews are hidden; deliberately names neither the sender nor the content")
|
||||
}
|
||||
static var mentionTitle: String {
|
||||
String(localized: "notification.redacted.mention.title", defaultValue: "🫵 you were mentioned", comment: "Lock-screen notification title telling someone they were mentioned when message previews are hidden; deliberately omits who mentioned them")
|
||||
}
|
||||
static var geohashActivityTitle: String {
|
||||
String(localized: "notification.redacted.geohash.title", defaultValue: "📍 new activity nearby", comment: "Lock-screen notification title for activity in a location channel when message previews are hidden; deliberately omits the geohash")
|
||||
}
|
||||
static var body: String {
|
||||
String(localized: "notification.redacted.body", defaultValue: "open bitchat to read", comment: "Lock-screen notification body shown in place of the message text when message previews are hidden")
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether delivered alerts must withhold sender, content, and geohash.
|
||||
///
|
||||
/// Injected rather than read from the preference directly so tests state
|
||||
/// which behavior they are asserting instead of inheriting whatever the
|
||||
/// shared preference happens to hold when they run.
|
||||
private let hidePreviewsProvider: () -> Bool
|
||||
|
||||
private var hidePreviews: Bool {
|
||||
hidePreviewsProvider()
|
||||
}
|
||||
|
||||
private let isRunningTestsProvider: () -> Bool
|
||||
private let authorizer: NotificationAuthorizing
|
||||
private let requestDeliverer: NotificationRequestDelivering
|
||||
@@ -106,6 +135,7 @@ final class NotificationService {
|
||||
}
|
||||
|
||||
private init() {
|
||||
self.hidePreviewsProvider = { NotificationPrivacySettings.hideMessagePreviews }
|
||||
self.isRunningTestsProvider = {
|
||||
let env = ProcessInfo.processInfo.environment
|
||||
return NSClassFromString("XCTestCase") != nil ||
|
||||
@@ -130,12 +160,14 @@ final class NotificationService {
|
||||
isRunningTestsProvider: @escaping () -> Bool,
|
||||
authorizer: NotificationAuthorizing,
|
||||
requestDeliverer: NotificationRequestDelivering,
|
||||
categoryRegistrar: NotificationCategoryRegistering = NoopNotificationCategoryRegistrar()
|
||||
categoryRegistrar: NotificationCategoryRegistering = NoopNotificationCategoryRegistrar(),
|
||||
hidePreviewsProvider: @escaping () -> Bool = { NotificationPrivacySettings.hideMessagePreviews }
|
||||
) {
|
||||
self.isRunningTestsProvider = isRunningTestsProvider
|
||||
self.authorizer = authorizer
|
||||
self.requestDeliverer = requestDeliverer
|
||||
self.categoryRegistrar = categoryRegistrar
|
||||
self.hidePreviewsProvider = hidePreviewsProvider
|
||||
}
|
||||
|
||||
func requestAuthorization() {
|
||||
@@ -197,29 +229,34 @@ final class NotificationService {
|
||||
}
|
||||
|
||||
func sendMentionNotification(from sender: String, message: String) {
|
||||
let title = "🫵 you were mentioned by \(sender)"
|
||||
let body = message
|
||||
let title = hidePreviews ? Redacted.mentionTitle : "🫵 you were mentioned by \(sender)"
|
||||
let body = hidePreviews ? Redacted.body : message
|
||||
let identifier = "mention-\(UUID().uuidString)"
|
||||
|
||||
|
||||
sendLocalNotification(title: title, body: body, identifier: identifier)
|
||||
}
|
||||
|
||||
|
||||
func sendPrivateMessageNotification(from sender: String, message: String, peerID: PeerID) {
|
||||
let title = "🔒 DM from \(sender)"
|
||||
let body = message
|
||||
let title = hidePreviews ? Redacted.directMessageTitle : "🔒 DM from \(sender)"
|
||||
let body = hidePreviews ? Redacted.body : message
|
||||
let identifier = "private-\(UUID().uuidString)"
|
||||
// Routing payload, not display copy: `userInfo` never reaches the lock
|
||||
// screen, and the conversation to open still has to be identifiable.
|
||||
let userInfo = ["peerID": peerID.id, "senderName": sender]
|
||||
|
||||
|
||||
sendLocalNotification(title: title, body: body, identifier: identifier, userInfo: userInfo)
|
||||
}
|
||||
|
||||
|
||||
// Geohash public chat notification with deep link to a specific geohash
|
||||
func sendGeohashActivityNotification(geohash: String, titlePrefix: String = "#", bodyPreview: String) {
|
||||
let title = "\(titlePrefix)\(geohash)"
|
||||
// The geohash itself is location data, so hiding previews withholds it
|
||||
// from the alert while leaving the deep link intact for the tap.
|
||||
let title = hidePreviews ? Redacted.geohashActivityTitle : "\(titlePrefix)\(geohash)"
|
||||
let body = hidePreviews ? Redacted.body : bodyPreview
|
||||
let identifier = "geo-activity-\(geohash)-\(Date().timeIntervalSince1970)"
|
||||
let deeplink = "bitchat://geohash/\(geohash)"
|
||||
let userInfo: [String: Any] = ["deeplink": deeplink]
|
||||
sendLocalNotification(title: title, body: bodyPreview, identifier: identifier, userInfo: userInfo)
|
||||
sendLocalNotification(title: title, body: body, identifier: identifier, userInfo: userInfo)
|
||||
}
|
||||
|
||||
func sendNetworkAvailableNotification(peerCount: Int) {
|
||||
|
||||
@@ -293,6 +293,9 @@ protocol Transport: AnyObject {
|
||||
/// Drops any carried public messages from a (newly blocked) sender so
|
||||
/// they can't resurface as archived echoes on a later launch.
|
||||
func purgeArchivedPublicMessages(from peerID: PeerID)
|
||||
/// Erases the whole carried public-message archive, on disk included, so
|
||||
/// clearing the mesh timeline deletes that history rather than hiding it.
|
||||
func purgeAllArchivedPublicMessages()
|
||||
}
|
||||
|
||||
/// A carried public mesh message from the store-and-forward window, decoded
|
||||
@@ -403,6 +406,7 @@ extension Transport {
|
||||
}
|
||||
|
||||
func purgeArchivedPublicMessages(from peerID: PeerID) {}
|
||||
func purgeAllArchivedPublicMessages() {}
|
||||
}
|
||||
|
||||
protocol TransportPeerEventsDelegate: AnyObject {
|
||||
@@ -446,3 +450,6 @@ extension BitchatDelegate {
|
||||
}
|
||||
|
||||
extension BLEService: Transport {}
|
||||
extension BLEService: BluetoothStateReporting {}
|
||||
extension BLEService: PanicResettingTransport {}
|
||||
extension BLEService: MeshBridgingTransport {}
|
||||
|
||||
@@ -733,6 +733,26 @@ final class GossipSyncManager {
|
||||
}
|
||||
}
|
||||
|
||||
/// Drop every carried public message and clear the archive on disk.
|
||||
///
|
||||
/// Used when someone clears the mesh timeline: the watermark already stops
|
||||
/// cleared messages from being shown again, so anything left in the
|
||||
/// archive is retained purely to serve other peers — and a person who
|
||||
/// clears a timeline reasonably reads that as "this is gone from my
|
||||
/// phone". The cost is that this device stops offering the recent public
|
||||
/// backlog to peers until it hears fresh traffic.
|
||||
func removeAllPublicMessages() {
|
||||
queue.async { [weak self] in
|
||||
guard let self else { return }
|
||||
self.messages.remove { _ in true }
|
||||
self.archiveDirty = true
|
||||
// Persist now rather than waiting for maintenance: a relaunch in
|
||||
// the gap would restore the purged messages from disk.
|
||||
self.persistArchiveIfDirty()
|
||||
self.archive?.wipe()
|
||||
}
|
||||
}
|
||||
|
||||
private func removeState(for peerID: PeerID) {
|
||||
// Deliberately keeps the peer's prekey bundle: bundles exist to reach
|
||||
// owners who left the mesh, and they age out on their own schedule.
|
||||
|
||||
@@ -21,6 +21,14 @@ protocol ChatDeliveryContext: AnyObject {
|
||||
/// message is unknown or no copy changed.
|
||||
@discardableResult
|
||||
func setDeliveryStatus(_ status: DeliveryStatus, forMessageID messageID: String) -> Bool
|
||||
/// Applies an authenticated receipt only to the direct conversations
|
||||
/// represented by the supplied peer aliases.
|
||||
@discardableResult
|
||||
func setDeliveryStatus(
|
||||
_ status: DeliveryStatus,
|
||||
forMessageID messageID: String,
|
||||
inDirectPeerAliases peerIDs: Set<PeerID>
|
||||
) -> Bool
|
||||
/// Current delivery status of the message in whichever conversation holds it.
|
||||
func deliveryStatus(forMessageID messageID: String) -> DeliveryStatus?
|
||||
/// Message IDs across all direct conversations (read-receipt pruning).
|
||||
@@ -33,6 +41,19 @@ protocol ChatDeliveryContext: AnyObject {
|
||||
func notifyUIChanged()
|
||||
/// Confirms receipt so the message router stops retaining the message for resend.
|
||||
func markMessageDelivered(_ messageID: String)
|
||||
/// Peer-bound form for authenticated remote receipts. Only the supplied
|
||||
/// conversation aliases may have retained state terminalized. This is the
|
||||
/// router-side clear only: it is safe without a conversation lookup
|
||||
/// because the router scopes removal to the acking peer's own queues.
|
||||
func markMessageDelivered(_ messageID: String, from peerIDs: Set<PeerID>)
|
||||
/// Releases the media reconnect retry for a private transfer. Unlike the
|
||||
/// router clear above this is keyed only by the stable media message ID,
|
||||
/// so callers must first bind the receipt to one of our outgoing
|
||||
/// conversations for the acking peer.
|
||||
func confirmPrivateMediaDelivery(_ messageID: String)
|
||||
/// Returns true only when `messageID` is one of our outgoing messages in
|
||||
/// at least one of the authenticated peer's direct-conversation aliases.
|
||||
func isOutgoingPrivateMessage(_ messageID: String, toAny peerIDs: Set<PeerID>) -> Bool
|
||||
}
|
||||
|
||||
extension ChatViewModel: ChatDeliveryContext {
|
||||
@@ -41,6 +62,19 @@ extension ChatViewModel: ChatDeliveryContext {
|
||||
conversations.setDeliveryStatus(status, forMessageID: messageID)
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
func setDeliveryStatus(
|
||||
_ status: DeliveryStatus,
|
||||
forMessageID messageID: String,
|
||||
inDirectPeerAliases peerIDs: Set<PeerID>
|
||||
) -> Bool {
|
||||
conversations.setDeliveryStatus(
|
||||
status,
|
||||
forMessageID: messageID,
|
||||
inDirectPeerAliases: peerIDs
|
||||
)
|
||||
}
|
||||
|
||||
func deliveryStatus(forMessageID messageID: String) -> DeliveryStatus? {
|
||||
conversations.deliveryStatus(forMessageID: messageID)
|
||||
}
|
||||
@@ -59,6 +93,24 @@ extension ChatViewModel: ChatDeliveryContext {
|
||||
messageID: messageID
|
||||
)
|
||||
}
|
||||
|
||||
func markMessageDelivered(_ messageID: String, from peerIDs: Set<PeerID>) {
|
||||
messageRouter.markDelivered(messageID, from: peerIDs)
|
||||
}
|
||||
|
||||
func confirmPrivateMediaDelivery(_ messageID: String) {
|
||||
mediaTransferCoordinator.confirmPrivateMediaDelivery(
|
||||
messageID: messageID
|
||||
)
|
||||
}
|
||||
|
||||
func isOutgoingPrivateMessage(_ messageID: String, toAny peerIDs: Set<PeerID>) -> Bool {
|
||||
peerIDs.contains { peerID in
|
||||
privateMessages(for: peerID).contains { message in
|
||||
message.id == messageID && message.senderPeerID == myPeerID
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Thin mapper from delivery events (read receipts, transport delivery
|
||||
@@ -86,9 +138,10 @@ final class ChatDeliveryCoordinator {
|
||||
|
||||
@MainActor
|
||||
func didReceiveReadReceipt(_ receipt: ReadReceipt) {
|
||||
updateMessageDeliveryStatus(
|
||||
updateAcknowledgedMessageDeliveryStatus(
|
||||
receipt.originalMessageID,
|
||||
status: .read(by: receipt.readerNickname, at: receipt.timestamp)
|
||||
status: .read(by: receipt.readerNickname, at: receipt.timestamp),
|
||||
from: [receipt.readerID]
|
||||
)
|
||||
}
|
||||
|
||||
@@ -105,17 +158,59 @@ final class ChatDeliveryCoordinator {
|
||||
@MainActor
|
||||
@discardableResult
|
||||
func updateMessageDeliveryStatus(_ messageID: String, status: DeliveryStatus) -> Bool {
|
||||
guard context.setDeliveryStatus(status, forMessageID: messageID) else {
|
||||
return false
|
||||
}
|
||||
switch status {
|
||||
case .delivered, .read:
|
||||
// Confirmed receipt — stop retaining the message for resend.
|
||||
// Terminalize only after the store accepted the transition.
|
||||
context.markMessageDelivered(messageID)
|
||||
default:
|
||||
break
|
||||
}
|
||||
context.notifyUIChanged()
|
||||
return true
|
||||
}
|
||||
|
||||
guard context.setDeliveryStatus(status, forMessageID: messageID) else {
|
||||
/// Applies an authenticated remote delivery/read receipt. The durable
|
||||
/// retry state is always released for the acking peer's own aliases
|
||||
/// (`markMessageDelivered(_:from:)` is peer-scoped on the router side, so
|
||||
/// a receipt can only terminalize messages queued for that peer). Only the
|
||||
/// UI status transition and the media-retry release are gated on the
|
||||
/// in-memory conversation holding the message as one of ours: after a
|
||||
/// force-quit → relaunch the durable outbox is restored
|
||||
/// while the conversation may not be, and discarding the ack there would
|
||||
/// re-send an already-delivered message on every flush/auth event until
|
||||
/// the attempt cap marks it failed. Mirrors the Nostr path
|
||||
/// (`ChatPrivateConversationCoordinator.handleDelivered`), which clears
|
||||
/// retained state unconditionally.
|
||||
@MainActor
|
||||
@discardableResult
|
||||
func updateAcknowledgedMessageDeliveryStatus(
|
||||
_ messageID: String,
|
||||
status: DeliveryStatus,
|
||||
from peerIDAliases: Set<PeerID>
|
||||
) -> Bool {
|
||||
switch status {
|
||||
case .delivered, .read:
|
||||
break
|
||||
default:
|
||||
return false
|
||||
}
|
||||
guard !peerIDAliases.isEmpty else { return false }
|
||||
context.markMessageDelivered(messageID, from: peerIDAliases)
|
||||
guard context.isOutgoingPrivateMessage(messageID, toAny: peerIDAliases),
|
||||
context.setDeliveryStatus(
|
||||
status,
|
||||
forMessageID: messageID,
|
||||
inDirectPeerAliases: peerIDAliases
|
||||
) else {
|
||||
return false
|
||||
}
|
||||
// The receipt is now bound to one of our outgoing conversations for
|
||||
// the acking peer; only then release the media reconnect retry, whose
|
||||
// stable message ID is not peer-scoped.
|
||||
context.confirmPrivateMediaDelivery(messageID)
|
||||
context.notifyUIChanged()
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -106,8 +106,8 @@ extension ChatViewModel: ChatLifecycleContext {
|
||||
}
|
||||
|
||||
func refreshBluetoothState() {
|
||||
if let bleService = meshService as? BLEService {
|
||||
updateBluetoothState(bleService.getCurrentBluetoothState())
|
||||
if let radio = meshService as? BluetoothStateReporting {
|
||||
updateBluetoothState(radio.getCurrentBluetoothState())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -85,6 +85,11 @@ protocol ChatPrivateConversationContext: AnyObject {
|
||||
func routePrivateMessage(_ content: String, to peerID: PeerID, recipientNickname: String, messageID: String)
|
||||
@discardableResult
|
||||
func routeReadReceipt(_ receipt: ReadReceipt, to peerID: PeerID) -> Bool
|
||||
/// Confirms an authenticated delivery/read acknowledgement so the router
|
||||
/// stops retaining the original private message for resend. The peer
|
||||
/// aliases scope the removal to the authenticated sender.
|
||||
@discardableResult
|
||||
func markMessageDelivered(_ messageID: String, for peerIDs: [PeerID]) -> Bool
|
||||
func sendMeshReadReceipt(_ receipt: ReadReceipt, to peerID: PeerID)
|
||||
func sendGeohashPrivateMessage(_ content: String, toRecipientHex recipientHex: String, from identity: NostrIdentity, messageID: String)
|
||||
func sendGeohashDeliveryAck(for messageID: String, toRecipientHex recipientHex: String, from identity: NostrIdentity)
|
||||
@@ -166,6 +171,11 @@ extension ChatViewModel: ChatPrivateConversationContext {
|
||||
messageRouter.sendReadReceipt(receipt, to: peerID)
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
func markMessageDelivered(_ messageID: String, for peerIDs: [PeerID]) -> Bool {
|
||||
messageRouter.markDelivered(messageID, for: peerIDs)
|
||||
}
|
||||
|
||||
func routeFavoriteNotification(to peerID: PeerID, isFavorite: Bool) {
|
||||
messageRouter.sendFavoriteNotification(to: peerID, isFavorite: isFavorite)
|
||||
}
|
||||
@@ -250,6 +260,60 @@ final class ChatPrivateConversationCoordinator {
|
||||
return true
|
||||
}
|
||||
|
||||
/// Account DMs can arrive under the authenticated peer's full Noise key
|
||||
/// while an existing mesh conversation is keyed by its derived short ID.
|
||||
/// These are the only aliases we may safely join: the short ID is derived
|
||||
/// directly from the authenticated key, rather than guessed from a
|
||||
/// nickname or found by scanning unrelated chats.
|
||||
private func accountConversationAliases(for peerID: PeerID) -> [PeerID] {
|
||||
guard peerID.noiseKey != nil else { return [peerID] }
|
||||
let shortPeerID = peerID.toShort()
|
||||
return shortPeerID == peerID ? [peerID] : [peerID, shortPeerID]
|
||||
}
|
||||
|
||||
/// Keeps a connected account DM on its short routing ID and an offline DM
|
||||
/// on its stable Noise-key ID, folding the other authenticated alias into
|
||||
/// it and handing an open sheet across without closing it.
|
||||
private func consolidateAccountConversationAliases(for peerID: PeerID) -> PeerID {
|
||||
let aliases = accountConversationAliases(for: peerID)
|
||||
guard aliases.count > 1 else { return peerID }
|
||||
|
||||
let shortPeerID = peerID.toShort()
|
||||
let targetPeerID = context.isPeerConnected(shortPeerID) ? shortPeerID : peerID
|
||||
let sourcePeerIDs = aliases.filter { $0 != targetPeerID }
|
||||
|
||||
for sourcePeerID in sourcePeerIDs where !context.privateMessages(for: sourcePeerID).isEmpty {
|
||||
context.migratePrivateChat(from: sourcePeerID, to: targetPeerID)
|
||||
// ConversationStore deliberately preserves message values during a
|
||||
// generic migration, including its destination-wins rule for
|
||||
// duplicate IDs. Rewrite the resulting canonical copies so later
|
||||
// read-receipt scans compare against the new routing key without
|
||||
// replacing a newer destination value with the source snapshot.
|
||||
let canonicalMessages = context.privateMessages(for: targetPeerID)
|
||||
for message in canonicalMessages where message.senderPeerID == sourcePeerID {
|
||||
context.upsertPrivateMessage(
|
||||
BitchatMessage(
|
||||
id: message.id,
|
||||
sender: message.sender,
|
||||
content: message.content,
|
||||
timestamp: message.timestamp,
|
||||
isRelay: message.isRelay,
|
||||
originalSender: message.originalSender,
|
||||
isPrivate: message.isPrivate,
|
||||
recipientNickname: message.recipientNickname,
|
||||
senderPeerID: targetPeerID,
|
||||
mentions: message.mentions,
|
||||
deliveryStatus: message.deliveryStatus,
|
||||
isBridged: message.isBridged
|
||||
),
|
||||
in: targetPeerID
|
||||
)
|
||||
}
|
||||
}
|
||||
context.handOffSelectedPrivateChat(from: sourcePeerIDs, to: targetPeerID)
|
||||
return targetPeerID
|
||||
}
|
||||
|
||||
func sendPrivateMessage(_ content: String, to peerID: PeerID) {
|
||||
guard !content.isEmpty else { return }
|
||||
|
||||
@@ -464,6 +528,8 @@ final class ChatPrivateConversationCoordinator {
|
||||
return
|
||||
}
|
||||
|
||||
let conversationPeerID = consolidateAccountConversationAliases(for: convKey)
|
||||
|
||||
if context.privateChatsContainMessage(withID: messageId) { return }
|
||||
|
||||
let message = BitchatMessage(
|
||||
@@ -474,18 +540,18 @@ final class ChatPrivateConversationCoordinator {
|
||||
isRelay: false,
|
||||
isPrivate: true,
|
||||
recipientNickname: context.nickname,
|
||||
senderPeerID: convKey,
|
||||
senderPeerID: conversationPeerID,
|
||||
deliveryStatus: .delivered(to: context.nickname, at: Date())
|
||||
)
|
||||
|
||||
context.appendPrivateMessage(message, to: convKey)
|
||||
context.appendPrivateMessage(message, to: conversationPeerID)
|
||||
|
||||
let isViewing = context.selectedPrivateChatPeer == convKey
|
||||
let isViewing = context.selectedPrivateChatPeer == conversationPeerID
|
||||
let wasReadBefore = context.sentReadReceipts.contains(messageId)
|
||||
let isRecentMessage = Date().timeIntervalSince(messageTimestamp) < 30
|
||||
let shouldMarkUnread = !wasReadBefore && !isViewing && isRecentMessage
|
||||
if shouldMarkUnread {
|
||||
context.markPrivateChatUnread(convKey)
|
||||
context.markPrivateChatUnread(conversationPeerID)
|
||||
}
|
||||
|
||||
if isViewing {
|
||||
@@ -493,7 +559,7 @@ final class ChatPrivateConversationCoordinator {
|
||||
}
|
||||
|
||||
if !isViewing && shouldMarkUnread {
|
||||
context.notifyPrivateMessage(from: senderName, message: pm.content, peerID: convKey)
|
||||
context.notifyPrivateMessage(from: senderName, message: pm.content, peerID: conversationPeerID)
|
||||
}
|
||||
|
||||
context.notifyUIChanged()
|
||||
@@ -502,17 +568,32 @@ final class ChatPrivateConversationCoordinator {
|
||||
func handleDelivered(_ payload: NoisePayload, senderPubkey: String, convKey: PeerID) {
|
||||
guard let messageID = String(data: payload.data, encoding: .utf8) else { return }
|
||||
|
||||
if context.privateChat(convKey, containsMessageWithID: messageID) {
|
||||
context.setPrivateDeliveryStatus(
|
||||
let aliases = accountConversationAliases(for: convKey)
|
||||
let clearedRetainedMessage = convKey.noiseKey != nil
|
||||
? context.markMessageDelivered(messageID, for: aliases)
|
||||
: false
|
||||
let hasConversationMessage = aliases.contains {
|
||||
context.privateChat($0, containsMessageWithID: messageID)
|
||||
}
|
||||
if hasConversationMessage {
|
||||
let conversationPeerID = consolidateAccountConversationAliases(for: convKey)
|
||||
let didChange = context.setPrivateDeliveryStatus(
|
||||
.delivered(to: context.displayNameForNostrPubkey(senderPubkey), at: Date()),
|
||||
forMessageID: messageID,
|
||||
peerID: convKey
|
||||
peerID: conversationPeerID
|
||||
)
|
||||
context.notifyUIChanged()
|
||||
if didChange {
|
||||
context.notifyUIChanged()
|
||||
}
|
||||
SecureLogger.info(
|
||||
"GeoDM: recv DELIVERED for mid=\(messageID.prefix(8))… from=\(senderPubkey.prefix(8))…",
|
||||
category: .session
|
||||
)
|
||||
} else if clearedRetainedMessage {
|
||||
SecureLogger.debug(
|
||||
"GeoDM: recv DELIVERED for cleared mid=\(messageID.prefix(8))… from=\(senderPubkey.prefix(8))…",
|
||||
category: .session
|
||||
)
|
||||
} else {
|
||||
// A stale ack for a message this device no longer tracks (dropped
|
||||
// outbox entry, cleared chat, or a peer re-acking after losing our
|
||||
@@ -524,14 +605,29 @@ final class ChatPrivateConversationCoordinator {
|
||||
func handleReadReceipt(_ payload: NoisePayload, senderPubkey: String, convKey: PeerID) {
|
||||
guard let messageID = String(data: payload.data, encoding: .utf8) else { return }
|
||||
|
||||
if context.privateChat(convKey, containsMessageWithID: messageID) {
|
||||
context.setPrivateDeliveryStatus(
|
||||
let aliases = accountConversationAliases(for: convKey)
|
||||
let clearedRetainedMessage = convKey.noiseKey != nil
|
||||
? context.markMessageDelivered(messageID, for: aliases)
|
||||
: false
|
||||
let hasConversationMessage = aliases.contains {
|
||||
context.privateChat($0, containsMessageWithID: messageID)
|
||||
}
|
||||
if hasConversationMessage {
|
||||
let conversationPeerID = consolidateAccountConversationAliases(for: convKey)
|
||||
let didChange = context.setPrivateDeliveryStatus(
|
||||
.read(by: context.displayNameForNostrPubkey(senderPubkey), at: Date()),
|
||||
forMessageID: messageID,
|
||||
peerID: convKey
|
||||
peerID: conversationPeerID
|
||||
)
|
||||
context.notifyUIChanged()
|
||||
if didChange {
|
||||
context.notifyUIChanged()
|
||||
}
|
||||
SecureLogger.info("GeoDM: recv READ for mid=\(messageID.prefix(8))… from=\(senderPubkey.prefix(8))…", category: .session)
|
||||
} else if clearedRetainedMessage {
|
||||
SecureLogger.debug(
|
||||
"GeoDM: recv READ for cleared mid=\(messageID.prefix(8))… from=\(senderPubkey.prefix(8))…",
|
||||
category: .session
|
||||
)
|
||||
} else {
|
||||
SecureLogger.warning("GeoDM: read ack for unknown mid=\(messageID.prefix(8))… conv=\(convKey)", category: .session)
|
||||
}
|
||||
|
||||
@@ -44,6 +44,9 @@ protocol ChatPublicConversationContext: AnyObject {
|
||||
func removePublicMessages(fromGeohash geohash: String, where predicate: (BitchatMessage) -> Bool)
|
||||
/// Empties a public conversation's timeline (`/clear`).
|
||||
func clearPublicConversation(_ conversationID: ConversationID)
|
||||
/// Erases the on-disk archive of carried public mesh messages, so clearing
|
||||
/// the mesh timeline deletes that history instead of only hiding it.
|
||||
func purgeArchivedPublicMessages()
|
||||
/// Queues a system message for the next geohash channel visit.
|
||||
func queueGeohashSystemMessage(_ content: String)
|
||||
|
||||
@@ -289,12 +292,14 @@ final class ChatPublicConversationCoordinator: PublicMessagePipelineDelegate {
|
||||
context.clearPublicConversation(ConversationID(channelID: context.activeChannel))
|
||||
|
||||
// Clearing the mesh timeline also dismisses its archived echoes for
|
||||
// good: the watermark stops the next launch from re-seeding them
|
||||
// (the archive itself keeps carrying the messages for peers), and
|
||||
// the dedup keys go so a cleared message arriving live shows again.
|
||||
// good: the watermark stops the next launch from re-seeding them, the
|
||||
// archive on disk is erased so the cleared history is actually gone
|
||||
// rather than merely hidden, and the dedup keys go so a cleared
|
||||
// message arriving live shows again.
|
||||
if case .mesh = context.activeChannel {
|
||||
MeshEchoSettings.clearedThrough = Date()
|
||||
archivedEchoKeys.removeAll()
|
||||
context.purgeArchivedPublicMessages()
|
||||
}
|
||||
|
||||
// The SPM test process shares the real Application Support tree, so this
|
||||
|
||||
@@ -62,10 +62,15 @@ protocol ChatTransportEventContext: AnyObject {
|
||||
func sendMeshDeliveryAck(for messageID: String, to peerID: PeerID)
|
||||
|
||||
// MARK: Delivery status
|
||||
/// Applies the status to every known location of the message.
|
||||
/// Returns `false` when no message with that ID was updated.
|
||||
/// Applies an authenticated receipt to the message only when it belongs
|
||||
/// to the supplied peer conversation aliases. Returns `false` for an
|
||||
/// unknown ID, wrong peer, or rejected status transition.
|
||||
@discardableResult
|
||||
func applyMessageDeliveryStatus(_ messageID: String, status: DeliveryStatus) -> Bool
|
||||
func applyAcknowledgedMessageDeliveryStatus(
|
||||
_ messageID: String,
|
||||
status: DeliveryStatus,
|
||||
from peerIDAliases: Set<PeerID>
|
||||
) -> Bool
|
||||
func deliveryStatus(for messageID: String) -> DeliveryStatus?
|
||||
|
||||
// MARK: Verification payloads
|
||||
@@ -122,8 +127,16 @@ extension ChatViewModel: ChatTransportEventContext {
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
func applyMessageDeliveryStatus(_ messageID: String, status: DeliveryStatus) -> Bool {
|
||||
deliveryCoordinator.updateMessageDeliveryStatus(messageID, status: status)
|
||||
func applyAcknowledgedMessageDeliveryStatus(
|
||||
_ messageID: String,
|
||||
status: DeliveryStatus,
|
||||
from peerIDAliases: Set<PeerID>
|
||||
) -> Bool {
|
||||
deliveryCoordinator.updateAcknowledgedMessageDeliveryStatus(
|
||||
messageID,
|
||||
status: status,
|
||||
from: peerIDAliases
|
||||
)
|
||||
}
|
||||
|
||||
func deliveryStatus(for messageID: String) -> DeliveryStatus? {
|
||||
@@ -446,9 +459,10 @@ private extension ChatTransportEventCoordinator {
|
||||
guard let messageID = String(data: payload, encoding: .utf8) else { return }
|
||||
|
||||
let name = deliveryStatusName(for: peerID, in: context)
|
||||
let didUpdate = context.applyMessageDeliveryStatus(
|
||||
let didUpdate = context.applyAcknowledgedMessageDeliveryStatus(
|
||||
messageID,
|
||||
status: .delivered(to: name, at: Date())
|
||||
status: .delivered(to: name, at: Date()),
|
||||
from: receiptPeerAliases(for: peerID, in: context)
|
||||
)
|
||||
|
||||
if !didUpdate {
|
||||
@@ -463,9 +477,10 @@ private extension ChatTransportEventCoordinator {
|
||||
guard let messageID = String(data: payload, encoding: .utf8) else { return }
|
||||
|
||||
let name = deliveryStatusName(for: peerID, in: context)
|
||||
let didUpdate = context.applyMessageDeliveryStatus(
|
||||
let didUpdate = context.applyAcknowledgedMessageDeliveryStatus(
|
||||
messageID,
|
||||
status: .read(by: name, at: Date())
|
||||
status: .read(by: name, at: Date()),
|
||||
from: receiptPeerAliases(for: peerID, in: context)
|
||||
)
|
||||
|
||||
if !didUpdate {
|
||||
@@ -503,4 +518,21 @@ private extension ChatTransportEventCoordinator {
|
||||
func deliveryStatusName(for peerID: PeerID, in context: any ChatTransportEventContext) -> String {
|
||||
context.unifiedPeer(for: peerID)?.nickname ?? context.resolveNickname(for: peerID)
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func receiptPeerAliases(
|
||||
for peerID: PeerID,
|
||||
in context: any ChatTransportEventContext
|
||||
) -> Set<PeerID> {
|
||||
var aliases: Set<PeerID> = [peerID]
|
||||
// The active authenticated Noise key is authoritative. A cached
|
||||
// ephemeral→stable mapping can predate an identity replacement, so
|
||||
// use it only when the live session cannot provide its static key.
|
||||
if let keyData = context.noiseSessionPublicKeyData(for: peerID) {
|
||||
aliases.insert(PeerID(hexData: keyData))
|
||||
} else if let stablePeerID = context.cachedStablePeerID(for: peerID) {
|
||||
aliases.insert(stablePeerID)
|
||||
}
|
||||
return aliases
|
||||
}
|
||||
}
|
||||
|
||||
@@ -59,6 +59,10 @@ protocol ChatVerificationContext: AnyObject {
|
||||
func hasEstablishedNoiseSession(with peerID: PeerID) -> Bool
|
||||
func triggerHandshake(with peerID: PeerID)
|
||||
func privateMediaPeerDidAuthenticate(_ peerID: PeerID)
|
||||
/// Retries only private messages previously transmitted through a secure
|
||||
/// session and still pending an ack. Both ephemeral and stable aliases
|
||||
/// are supplied because either can own the outbox entry.
|
||||
func retrySecurePrivateMessagesAfterAuthentication(for peerIDAliases: [PeerID])
|
||||
func sendVerifyChallenge(to peerID: PeerID, noiseKeyHex: String, nonceA: Data)
|
||||
func sendVerifyResponse(to peerID: PeerID, noiseKeyHex: String, nonceA: Data)
|
||||
|
||||
@@ -121,6 +125,10 @@ extension ChatViewModel: ChatVerificationContext {
|
||||
mediaTransferCoordinator.peerDidAuthenticate(peerID.toShort())
|
||||
}
|
||||
|
||||
func retrySecurePrivateMessagesAfterAuthentication(for peerIDAliases: [PeerID]) {
|
||||
messageRouter.retrySecurePrivateMessagesAfterAuthentication(for: peerIDAliases)
|
||||
}
|
||||
|
||||
func sendVerifyChallenge(to peerID: PeerID, noiseKeyHex: String, nonceA: Data) {
|
||||
meshService.sendVerifyChallenge(to: peerID, noiseKeyHex: noiseKeyHex, nonceA: nonceA)
|
||||
}
|
||||
@@ -216,16 +224,37 @@ final class ChatVerificationCoordinator {
|
||||
|
||||
self.context.invalidateEncryptionCache(for: peerID)
|
||||
|
||||
if self.context.cachedStablePeerID(for: peerID) == nil,
|
||||
let keyData = self.context.noiseSessionPublicKeyData(for: peerID) {
|
||||
var authenticatedStablePeerID: PeerID?
|
||||
if let keyData = self.context.noiseSessionPublicKeyData(for: peerID) {
|
||||
let stablePeerID = PeerID(hexData: keyData)
|
||||
self.context.cacheStablePeerID(stablePeerID, for: peerID)
|
||||
authenticatedStablePeerID = stablePeerID
|
||||
if self.context.cachedStablePeerID(for: peerID) != stablePeerID {
|
||||
// The freshly authenticated Noise key outranks a
|
||||
// stale announce-derived alias.
|
||||
self.context.cacheStablePeerID(stablePeerID, for: peerID)
|
||||
}
|
||||
SecureLogger.debug(
|
||||
"🗺️ Mapped short peerID to Noise key for header continuity: \(peerID) -> \(stablePeerID.id.prefix(8))…",
|
||||
category: .session
|
||||
)
|
||||
}
|
||||
|
||||
// A locally established session may have belonged to the
|
||||
// peer's previous app process. The first ciphertext sent
|
||||
// into that stale session is retained by MessageRouter;
|
||||
// retry it now that this newly authenticated/replacement
|
||||
// session can actually decrypt it.
|
||||
var peerIDAliases = [peerID]
|
||||
if let stablePeerID = authenticatedStablePeerID
|
||||
?? self.context.cachedStablePeerID(for: peerID),
|
||||
stablePeerID != peerID {
|
||||
// Conversations can migrate from the ephemeral BLE ID
|
||||
// to the authenticated Noise-key ID. Retry both aliases
|
||||
// because either may own the retained outbox entry.
|
||||
peerIDAliases.append(stablePeerID)
|
||||
}
|
||||
self.context.retrySecurePrivateMessagesAfterAuthentication(for: peerIDAliases)
|
||||
|
||||
if var pending = self.pendingQRVerifications[peerID], pending.sent == false {
|
||||
self.context.sendVerifyChallenge(
|
||||
to: peerID,
|
||||
|
||||
@@ -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?
|
||||
@@ -1066,6 +1068,10 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage
|
||||
conversations.clear(conversationID)
|
||||
}
|
||||
|
||||
func purgeArchivedPublicMessages() {
|
||||
meshService.purgeAllArchivedPublicMessages()
|
||||
}
|
||||
|
||||
/// Queues a system message for the next geohash channel visit. (Tiny
|
||||
/// UI-flow queue formerly on `PublicTimelineStore`; it is notice text,
|
||||
/// not conversation state, so it stays on the owner.)
|
||||
@@ -1558,8 +1564,8 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage
|
||||
|
||||
// Quiesce the mesh before clearing stores. Identity replacement below
|
||||
// deliberately stays stopped until media deletion and marker commit.
|
||||
if let bleService = meshService as? BLEService {
|
||||
bleService.suspendForPanicReset()
|
||||
if let panicTransport = meshService as? PanicResettingTransport {
|
||||
panicTransport.suspendForPanicReset()
|
||||
} else {
|
||||
meshService.emergencyDisconnectAll()
|
||||
}
|
||||
@@ -1628,6 +1634,10 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage
|
||||
GeohashChatActivityTracker.shared.clear()
|
||||
MeshSightingsTracker.shared.clear()
|
||||
MeshEchoSettings.reset()
|
||||
NotificationPrivacySettings.reset()
|
||||
// A hand-added relay names an operator someone chose to route through,
|
||||
// which is the kind of trace a wipe should not leave behind.
|
||||
NostrRelaySettings.reset()
|
||||
|
||||
// Drop private group keys and rosters (keychain + disk)
|
||||
groupStore.wipe()
|
||||
@@ -1690,8 +1700,8 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage
|
||||
|
||||
// Replace the BLE identity while keeping the radio stopped. It may
|
||||
// reopen only after the durable panic transaction commits.
|
||||
if let bleService = meshService as? BLEService {
|
||||
bleService.resetIdentityForPanic(
|
||||
if let panicTransport = meshService as? PanicResettingTransport {
|
||||
panicTransport.resetIdentityForPanic(
|
||||
currentNickname: nickname,
|
||||
restartServices: false
|
||||
)
|
||||
@@ -1736,18 +1746,19 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage
|
||||
|
||||
guard panicCompleted else { return false }
|
||||
|
||||
if let bleService = meshService as? BLEService {
|
||||
if let panicTransport = meshService as? PanicResettingTransport {
|
||||
// Startup recovery reopens admission but leaves actual service
|
||||
// start to the bootstrapper immediately after this method.
|
||||
bleService.completePanicReset(
|
||||
panicTransport.completePanicReset(
|
||||
restartServices: restartServices
|
||||
)
|
||||
}
|
||||
|
||||
if restartServices {
|
||||
// All persistent state and media are gone. Bring each service back
|
||||
// only now, under the new identity.
|
||||
if !(meshService is BLEService) {
|
||||
// only now, under the new identity — a panic-resetting transport
|
||||
// owns its own restart sequencing above.
|
||||
if !(meshService is PanicResettingTransport) {
|
||||
meshService.startServices()
|
||||
}
|
||||
|
||||
|
||||
@@ -195,9 +195,8 @@ private extension ChatViewModelBootstrapper {
|
||||
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { [weak viewModel] in
|
||||
guard let viewModel,
|
||||
let bleService = viewModel.meshService as? BLEService else { return }
|
||||
let state = bleService.getCurrentBluetoothState()
|
||||
viewModel.updateBluetoothState(state)
|
||||
let radio = viewModel.meshService as? BluetoothStateReporting else { return }
|
||||
viewModel.updateBluetoothState(radio.getCurrentBluetoothState())
|
||||
}
|
||||
|
||||
viewModel.nostrRelayManager = NostrRelayManager.shared
|
||||
@@ -331,7 +330,7 @@ private extension ChatViewModelBootstrapper {
|
||||
func configureGateway() {
|
||||
// Gateway mode bridges BLE mesh <-> Nostr; a mock transport (tests)
|
||||
// has no carrier packets to bridge.
|
||||
guard let bleService = viewModel.meshService as? BLEService else { return }
|
||||
guard let bleService = viewModel.meshService as? MeshBridgingTransport else { return }
|
||||
let gateway = GatewayService.shared
|
||||
|
||||
gateway.publishToRelays = { event, geohash in
|
||||
@@ -410,7 +409,7 @@ private extension ChatViewModelBootstrapper {
|
||||
/// transport, the relay manager, location, and the public timeline. Same
|
||||
/// closure-injection style as `configureGateway`.
|
||||
func configureBridge() {
|
||||
guard let bleService = viewModel.meshService as? BLEService else { return }
|
||||
guard let bleService = viewModel.meshService as? MeshBridgingTransport else { return }
|
||||
let bridge = BridgeService.shared
|
||||
let idBridge = viewModel.idBridge
|
||||
|
||||
@@ -545,7 +544,7 @@ private extension ChatViewModelBootstrapper {
|
||||
/// manager, the mesh transport's sealing/opening primitives, the courier
|
||||
/// store, and the message router's deposit path.
|
||||
func configureBridgeCourier() {
|
||||
guard let bleService = viewModel.meshService as? BLEService else { return }
|
||||
guard let bleService = viewModel.meshService as? MeshBridgingTransport else { return }
|
||||
let courier = BridgeCourierService.shared
|
||||
|
||||
courier.bridgeEnabled = { BridgeService.shared.isEnabled }
|
||||
|
||||
@@ -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,35 @@ 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 }
|
||||
// torEnforced is a compile-time constant in release builds; the
|
||||
// runtime preference is what says whether anyone is waiting on
|
||||
// Tor. Turning Tor off mid-bootstrap must not read as blocking.
|
||||
guard NetworkActivationService.persistedTorPreference() 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,10 @@ struct AppInfoView: View {
|
||||
@State private var showTopology = false
|
||||
@State private var liveVoiceEnabled = PTTSettings.liveVoiceEnabled
|
||||
@State private var locationNotesEnabled = LocationNotesSettings.enabled
|
||||
@State private var hideMessagePreviews = NotificationPrivacySettings.hideMessagePreviews
|
||||
@State private var customRelays = NostrRelaySettings.customRelays()
|
||||
@State private var relayInput = ""
|
||||
@State private var relayError: String?
|
||||
@ObservedObject private var locationManager = LocationChannelManager.shared
|
||||
/// Sticky across opens: first-ever open lands on Info (the gentler
|
||||
/// introduction), and afterwards the sheet reopens wherever it was left.
|
||||
@@ -79,10 +83,41 @@ 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"
|
||||
|
||||
static let privacyTitle = String(localized: "app_info.settings.privacy.title", defaultValue: "PRIVACY", comment: "Section header (uppercase) for privacy settings such as hiding notification previews")
|
||||
static let hidePreviewsTitle = String(localized: "app_info.settings.hide_previews.title", defaultValue: "hide message previews", comment: "Title of the setting that keeps message text, sender names, and geohashes out of lock-screen notifications")
|
||||
static let hidePreviewsSubtitle = String(localized: "app_info.settings.hide_previews.subtitle", defaultValue: "notifications say that something arrived without showing the message, who sent it, or which location channel it came from. anyone holding your locked phone learns nothing from the lock screen. on by default.", comment: "Subtitle explaining what hiding notification message previews does")
|
||||
|
||||
static let dangerTitle = String(localized: "app_info.settings.danger.title", defaultValue: "DANGER ZONE", comment: "Section header (uppercase) for destructive actions in settings")
|
||||
static let panicButton = String(localized: "app_info.settings.danger.panic_button", defaultValue: "panic wipe", comment: "Button in the settings danger zone that erases all local data after confirmation")
|
||||
static let panicNote = String(localized: "app_info.settings.danger.panic_note", defaultValue: "erases all messages, keys, and identity. triple-tapping the bitchat/ logo does the same, instantly.", comment: "Caption under the panic wipe button explaining what it does and the triple-tap shortcut")
|
||||
@@ -410,11 +445,22 @@ struct AppInfoView: View {
|
||||
settingsCard {
|
||||
settingToggle(
|
||||
title: Text(Strings.Settings.torTitle),
|
||||
subtitle: Text(Strings.Settings.torSubtitle),
|
||||
subtitle: Text(verbatim: Strings.Settings.torSubtitle),
|
||||
isOn: torToggleBinding
|
||||
)
|
||||
// Turning tor off is not a location-channels-only choice, so
|
||||
// say what it costs while it is off rather than in the
|
||||
// subtitle everyone skims.
|
||||
if !locationChannelsModel.userTorEnabled {
|
||||
Text(verbatim: Strings.Settings.torOffWarning)
|
||||
.bitchatFont(size: 11)
|
||||
.foregroundColor(palette.alertRed)
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
}
|
||||
}
|
||||
|
||||
relaySettingsCard
|
||||
|
||||
// Location notes / dead drops (merged from main's flat
|
||||
// layout into the shared card + pill style). Turning it on
|
||||
// may need the location prompt; the permission control below
|
||||
@@ -477,6 +523,26 @@ struct AppInfoView: View {
|
||||
}
|
||||
}
|
||||
|
||||
// Privacy: what a locked, seized, or borrowed phone gives away
|
||||
// without being unlocked.
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
SectionHeader(verbatim: Strings.Settings.privacyTitle)
|
||||
|
||||
settingsCard {
|
||||
settingToggle(
|
||||
title: Text(verbatim: Strings.Settings.hidePreviewsTitle),
|
||||
subtitle: Text(verbatim: Strings.Settings.hidePreviewsSubtitle),
|
||||
isOn: Binding(
|
||||
get: { hideMessagePreviews },
|
||||
set: { newValue in
|
||||
hideMessagePreviews = newValue
|
||||
NotificationPrivacySettings.hideMessagePreviews = newValue
|
||||
}
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Danger zone
|
||||
if onPanicWipe != nil {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
@@ -538,6 +604,108 @@ struct AppInfoView: View {
|
||||
)
|
||||
}
|
||||
|
||||
/// Relay list editor. The built-in relays are four well-known hostnames, so
|
||||
/// a filter blocking four names ends internet-delivered private messages;
|
||||
/// adding one here is the only fix that does not need a new build.
|
||||
@ViewBuilder
|
||||
private var relaySettingsCard: some View {
|
||||
settingsCard {
|
||||
VStack(alignment: .leading, spacing: 2) {
|
||||
Text(verbatim: Strings.Settings.relaysTitle)
|
||||
.bitchatFont(size: 12, weight: .semibold)
|
||||
.foregroundColor(textColor)
|
||||
Text(verbatim: Strings.Settings.relaysSubtitle)
|
||||
.bitchatFont(size: 11)
|
||||
.foregroundColor(secondaryTextColor)
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
}
|
||||
|
||||
ForEach(NostrRelayManager.builtInRelayURLs.sorted(), id: \.self) { relay in
|
||||
HStack(spacing: 6) {
|
||||
Text(verbatim: relay)
|
||||
.bitchatFont(size: 11)
|
||||
.foregroundColor(secondaryTextColor)
|
||||
.lineLimit(1)
|
||||
.truncationMode(.middle)
|
||||
Spacer(minLength: 4)
|
||||
Text(verbatim: Strings.Settings.relayBuiltIn)
|
||||
.bitchatFont(size: 10)
|
||||
.foregroundColor(secondaryTextColor)
|
||||
}
|
||||
}
|
||||
|
||||
ForEach(customRelays, id: \.self) { relay in
|
||||
HStack(spacing: 6) {
|
||||
Text(verbatim: relay)
|
||||
.bitchatFont(size: 11)
|
||||
.foregroundColor(textColor)
|
||||
.lineLimit(1)
|
||||
.truncationMode(.middle)
|
||||
Spacer(minLength: 4)
|
||||
Button {
|
||||
NostrRelaySettings.remove(relay)
|
||||
reloadCustomRelays()
|
||||
} label: {
|
||||
Image(systemName: "minus.circle")
|
||||
.foregroundColor(palette.alertRed)
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.accessibilityLabel(Strings.Settings.relayRemove)
|
||||
}
|
||||
}
|
||||
|
||||
if customRelays.count < NostrRelaySettings.maxCustomRelays {
|
||||
HStack(spacing: 6) {
|
||||
TextField(Strings.Settings.relayPlaceholder, text: $relayInput)
|
||||
.textFieldStyle(.plain)
|
||||
.bitchatFont(size: 11)
|
||||
.foregroundColor(textColor)
|
||||
.autocorrectionDisabled(true)
|
||||
#if os(iOS)
|
||||
.textInputAutocapitalization(.never)
|
||||
.keyboardType(.URL)
|
||||
#endif
|
||||
.onSubmit(addRelay)
|
||||
Button(action: addRelay) {
|
||||
Text(verbatim: Strings.Settings.relayAdd)
|
||||
.bitchatFont(size: 11, weight: .semibold)
|
||||
.foregroundColor(palette.accent)
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.disabled(relayInput.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
|
||||
}
|
||||
}
|
||||
|
||||
if let relayError {
|
||||
Text(verbatim: relayError)
|
||||
.bitchatFont(size: 11)
|
||||
.foregroundColor(palette.alertRed)
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
}
|
||||
}
|
||||
// The store can change from outside this view — a panic wipe clears it —
|
||||
// so follow it rather than trusting the value read at creation.
|
||||
.onReceive(NotificationCenter.default.publisher(for: NostrRelaySettings.didChangeNotification)) { _ in
|
||||
reloadCustomRelays()
|
||||
}
|
||||
}
|
||||
|
||||
private func addRelay() {
|
||||
let candidate = relayInput
|
||||
switch NostrRelaySettings.add(candidate, builtIn: NostrRelayManager.builtInRelayURLs) {
|
||||
case .success:
|
||||
relayInput = ""
|
||||
relayError = nil
|
||||
reloadCustomRelays()
|
||||
case .failure(let failure):
|
||||
relayError = Strings.Settings.relayError(failure)
|
||||
}
|
||||
}
|
||||
|
||||
private func reloadCustomRelays() {
|
||||
customRelays = NostrRelaySettings.customRelays()
|
||||
}
|
||||
|
||||
private var torToggleBinding: Binding<Bool> {
|
||||
Binding(
|
||||
get: { locationChannelsModel.userTorEnabled },
|
||||
|
||||
@@ -73,7 +73,14 @@ struct ContentComposerView: View {
|
||||
.textInputAutocapitalization(.sentences)
|
||||
#endif
|
||||
.submitLabel(.send)
|
||||
.onSubmit(onSendMessage)
|
||||
.onSubmit {
|
||||
onSendMessage()
|
||||
// Only the return-key path: it steals focus on iOS, so
|
||||
// every message would cost a tap to reopen the keyboard.
|
||||
// The send button must not reopen a deliberately
|
||||
// dismissed keyboard, so it stays out of this.
|
||||
isTextFieldFocused.wrappedValue = true
|
||||
}
|
||||
.padding(.vertical, theme.usesGlassChrome ? 8 : 4)
|
||||
.padding(.horizontal, 6)
|
||||
.themedInputBackground()
|
||||
|
||||
@@ -6,11 +6,28 @@ import UIKit
|
||||
import AppKit
|
||||
#endif
|
||||
|
||||
struct ContentPeopleSheetModalPresentationState {
|
||||
var isImagePreviewPresented = false
|
||||
var isVerificationSheetPresented = false
|
||||
var legacyPrivateMediaConsentRequest: LegacyPrivateMediaConsentRequest? = nil
|
||||
var isVoiceAlertPresented = false
|
||||
var isMediaPickerPresented = false
|
||||
|
||||
var hasPresentation: Bool {
|
||||
isImagePreviewPresented
|
||||
|| isVerificationSheetPresented
|
||||
|| legacyPrivateMediaConsentRequest != nil
|
||||
|| isVoiceAlertPresented
|
||||
|| isMediaPickerPresented
|
||||
}
|
||||
}
|
||||
|
||||
struct ContentPeopleSheetView: View {
|
||||
@EnvironmentObject private var appChromeModel: AppChromeModel
|
||||
@EnvironmentObject private var privateConversationModel: PrivateConversationModel
|
||||
@EnvironmentObject private var verificationModel: VerificationModel
|
||||
@EnvironmentObject private var conversationUIModel: ConversationUIModel
|
||||
@Environment(\.scenePhase) private var scenePhase
|
||||
|
||||
@Binding var showSidebar: Bool
|
||||
@Binding var messageText: String
|
||||
@@ -23,6 +40,7 @@ struct ContentPeopleSheetView: View {
|
||||
var isTextFieldFocused: FocusState<Bool>.Binding
|
||||
@ObservedObject var voiceRecordingVM: VoiceRecordingViewModel
|
||||
@Binding var autocompleteDebounceTimer: Timer?
|
||||
@State private var showVerifySheet = false
|
||||
@ThemedPalette private var palette
|
||||
|
||||
let headerHeight: CGFloat
|
||||
@@ -35,6 +53,75 @@ struct ContentPeopleSheetView: View {
|
||||
@Binding var showMacImagePicker: Bool
|
||||
#endif
|
||||
|
||||
private func modalPresentationState(
|
||||
includingVoiceAlert: Bool
|
||||
) -> ContentPeopleSheetModalPresentationState {
|
||||
#if os(iOS)
|
||||
let isMediaPickerPresented = showImagePicker
|
||||
#else
|
||||
let isMediaPickerPresented = showMacImagePicker
|
||||
#endif
|
||||
|
||||
return ContentPeopleSheetModalPresentationState(
|
||||
isImagePreviewPresented: imagePreviewURL != nil,
|
||||
isVerificationSheetPresented: showVerifySheet,
|
||||
legacyPrivateMediaConsentRequest:
|
||||
conversationUIModel.legacyPrivateMediaConsentRequest,
|
||||
isVoiceAlertPresented: includingVoiceAlert && voiceRecordingVM.showAlert,
|
||||
isMediaPickerPresented: isMediaPickerPresented
|
||||
)
|
||||
}
|
||||
|
||||
private var hasModalPresentation: Bool {
|
||||
modalPresentationState(includingVoiceAlert: true).hasPresentation
|
||||
}
|
||||
|
||||
/// The voice alert cannot defer to itself: its own binding must keep
|
||||
/// reporting `true` while it is the presented modal.
|
||||
private var hasModalPresentationBesidesVoiceAlert: Bool {
|
||||
modalPresentationState(includingVoiceAlert: false).hasPresentation
|
||||
}
|
||||
|
||||
private var bluetoothAlertBinding: Binding<Bool> {
|
||||
Binding(
|
||||
get: {
|
||||
scenePhase == .active
|
||||
&& appChromeModel.showBluetoothAlert
|
||||
&& !hasModalPresentation
|
||||
},
|
||||
set: { isPresented in
|
||||
guard !isPresented,
|
||||
scenePhase == .active,
|
||||
!hasModalPresentation else {
|
||||
return
|
||||
}
|
||||
appChromeModel.showBluetoothAlert = false
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
/// Voice recording happens inside this sheet, so its error alert must
|
||||
/// present from here as well: the root copy defers whenever this sheet
|
||||
/// is up, exactly like the Bluetooth alert above. Presenting from the
|
||||
/// root instead would force-dismiss the sheet and end the conversation.
|
||||
private var voiceAlertBinding: Binding<Bool> {
|
||||
Binding(
|
||||
get: {
|
||||
scenePhase == .active
|
||||
&& voiceRecordingVM.showAlert
|
||||
&& !hasModalPresentationBesidesVoiceAlert
|
||||
},
|
||||
set: { isPresented in
|
||||
guard !isPresented,
|
||||
scenePhase == .active,
|
||||
!hasModalPresentationBesidesVoiceAlert else {
|
||||
return
|
||||
}
|
||||
voiceRecordingVM.showAlert = false
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
let legacyConsentRequest = conversationUIModel.legacyPrivateMediaConsentRequest
|
||||
NavigationStack {
|
||||
@@ -78,7 +165,8 @@ struct ContentPeopleSheetView: View {
|
||||
#endif
|
||||
} else {
|
||||
ContentPeopleListView(
|
||||
showSidebar: $showSidebar
|
||||
showSidebar: $showSidebar,
|
||||
showVerifySheet: $showVerifySheet
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -182,6 +270,27 @@ struct ContentPeopleSheetView: View {
|
||||
}
|
||||
}
|
||||
#endif
|
||||
.alert("Recording Error", isPresented: voiceAlertBinding, actions: {
|
||||
Button("common.ok", role: .cancel) {}
|
||||
if voiceRecordingVM.state == .permissionDenied {
|
||||
Button("location_channels.action.open_settings") {
|
||||
SystemSettings.microphone.open()
|
||||
}
|
||||
}
|
||||
}, message: {
|
||||
Text(voiceRecordingVM.state.alertMessage)
|
||||
})
|
||||
.alert(
|
||||
"content.alert.bluetooth_required.title",
|
||||
isPresented: bluetoothAlertBinding
|
||||
) {
|
||||
Button("content.alert.bluetooth_required.settings") {
|
||||
SystemSettings.bluetooth.open()
|
||||
}
|
||||
Button("common.ok", role: .cancel) {}
|
||||
} message: {
|
||||
Text(appChromeModel.bluetoothAlertMessage)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -196,8 +305,7 @@ private struct ContentPeopleListView: View {
|
||||
@ThemedPalette private var palette
|
||||
|
||||
@Binding var showSidebar: Bool
|
||||
|
||||
@State private var showVerifySheet = false
|
||||
@Binding var showVerifySheet: Bool
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
|
||||
@@ -14,6 +14,61 @@ import AppKit
|
||||
#endif
|
||||
import BitFoundation
|
||||
|
||||
struct ContentRootModalPresentationState {
|
||||
var isPeopleSheetPresented = false
|
||||
var isAppInfoPresented = false
|
||||
var isFingerprintPresented = false
|
||||
var isLocationChannelsSheetPresented = false
|
||||
var isNoticesSheetPresented = false
|
||||
var isImagePreviewPresented = false
|
||||
var isVerificationSheetPresented = false
|
||||
var isVoiceAlertPresented = false
|
||||
var isScreenshotPrivacyAlertPresented = false
|
||||
var isMediaPickerPresented = false
|
||||
|
||||
var hasPresentation: Bool {
|
||||
isPeopleSheetPresented
|
||||
|| isAppInfoPresented
|
||||
|| isFingerprintPresented
|
||||
|| isLocationChannelsSheetPresented
|
||||
|| isNoticesSheetPresented
|
||||
|| isImagePreviewPresented
|
||||
|| isVerificationSheetPresented
|
||||
|| isVoiceAlertPresented
|
||||
|| isScreenshotPrivacyAlertPresented
|
||||
|| isMediaPickerPresented
|
||||
}
|
||||
}
|
||||
|
||||
extension ContentRootModalPresentationState {
|
||||
@MainActor
|
||||
init(
|
||||
appChromeModel: AppChromeModel,
|
||||
isPeopleSheetPresented: Bool = false,
|
||||
isImagePreviewPresented: Bool = false,
|
||||
isVerificationSheetPresented: Bool = false,
|
||||
isVoiceAlertPresented: Bool = false,
|
||||
isMediaPickerPresented: Bool = false
|
||||
) {
|
||||
self.init(
|
||||
isPeopleSheetPresented: isPeopleSheetPresented,
|
||||
isAppInfoPresented: appChromeModel.isAppInfoPresented,
|
||||
isFingerprintPresented:
|
||||
appChromeModel.showingFingerprintFor != nil,
|
||||
isLocationChannelsSheetPresented:
|
||||
appChromeModel.isLocationChannelsSheetPresented,
|
||||
isNoticesSheetPresented:
|
||||
appChromeModel.isNoticesSheetPresented,
|
||||
isImagePreviewPresented: isImagePreviewPresented,
|
||||
isVerificationSheetPresented: isVerificationSheetPresented,
|
||||
isVoiceAlertPresented: isVoiceAlertPresented,
|
||||
isScreenshotPrivacyAlertPresented:
|
||||
appChromeModel.showScreenshotPrivacyWarning,
|
||||
isMediaPickerPresented: isMediaPickerPresented
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// On macOS 14+, disables the default system focus ring on TextFields.
|
||||
/// On earlier macOS versions and on iOS this is a no-op.
|
||||
struct FocusEffectDisabledModifier: ViewModifier {
|
||||
@@ -43,6 +98,7 @@ struct ContentView: View {
|
||||
@FocusState private var isTextFieldFocused: Bool
|
||||
@Environment(\.colorScheme) var colorScheme
|
||||
@Environment(\.appTheme) private var appTheme
|
||||
@Environment(\.scenePhase) private var scenePhase
|
||||
@State private var showSidebar = false
|
||||
@State private var selectedMessageSender: String?
|
||||
@State private var selectedMessageSenderID: PeerID?
|
||||
@@ -80,6 +136,80 @@ struct ContentView: View {
|
||||
|
||||
private var usesGlassLayout: Bool { appTheme.usesGlassChrome }
|
||||
|
||||
private var isPeopleSheetPresented: Bool {
|
||||
showSidebar || selectedPrivatePeerID != nil
|
||||
}
|
||||
|
||||
private func rootModalPresentationState(
|
||||
includingVoiceAlert: Bool
|
||||
) -> ContentRootModalPresentationState {
|
||||
#if os(iOS)
|
||||
let isMediaPickerPresented = showImagePicker
|
||||
#else
|
||||
let isMediaPickerPresented = showMacImagePicker
|
||||
#endif
|
||||
|
||||
return ContentRootModalPresentationState(
|
||||
appChromeModel: appChromeModel,
|
||||
isPeopleSheetPresented: isPeopleSheetPresented,
|
||||
isImagePreviewPresented: imagePreviewURL != nil,
|
||||
isVerificationSheetPresented: showVerifySheet,
|
||||
isVoiceAlertPresented: includingVoiceAlert && voiceRecordingVM.showAlert,
|
||||
isMediaPickerPresented: isMediaPickerPresented
|
||||
)
|
||||
}
|
||||
|
||||
private var hasRootModalPresentation: Bool {
|
||||
rootModalPresentationState(includingVoiceAlert: true).hasPresentation
|
||||
}
|
||||
|
||||
/// The voice alert cannot defer to itself: its own binding must keep
|
||||
/// reporting `true` while it is the presented modal.
|
||||
private var hasRootModalPresentationBesidesVoiceAlert: Bool {
|
||||
rootModalPresentationState(includingVoiceAlert: false).hasPresentation
|
||||
}
|
||||
|
||||
private var rootBluetoothAlertBinding: Binding<Bool> {
|
||||
Binding(
|
||||
get: {
|
||||
scenePhase == .active
|
||||
&& appChromeModel.showBluetoothAlert
|
||||
&& !hasRootModalPresentation
|
||||
},
|
||||
set: { isPresented in
|
||||
guard !isPresented,
|
||||
scenePhase == .active,
|
||||
!hasRootModalPresentation else {
|
||||
return
|
||||
}
|
||||
appChromeModel.showBluetoothAlert = false
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
/// Voice recording errors can surface while the people/DM sheet is up
|
||||
/// (recording happens inside the sheet). Presenting the root alert then
|
||||
/// would force-dismiss the sheet, so the root copy defers to any other
|
||||
/// root modal; the sheet presents its own copy. Mirrors the Bluetooth
|
||||
/// alert treatment above.
|
||||
private var rootVoiceAlertBinding: Binding<Bool> {
|
||||
Binding(
|
||||
get: {
|
||||
scenePhase == .active
|
||||
&& voiceRecordingVM.showAlert
|
||||
&& !hasRootModalPresentationBesidesVoiceAlert
|
||||
},
|
||||
set: { isPresented in
|
||||
guard !isPresented,
|
||||
scenePhase == .active,
|
||||
!hasRootModalPresentationBesidesVoiceAlert else {
|
||||
return
|
||||
}
|
||||
voiceRecordingVM.showAlert = false
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
mainContent
|
||||
.onAppear {
|
||||
@@ -121,11 +251,20 @@ struct ContentView: View {
|
||||
}
|
||||
.sheet(
|
||||
isPresented: Binding(
|
||||
get: { showSidebar || selectedPrivatePeerID != nil },
|
||||
get: { isPeopleSheetPresented },
|
||||
set: { isPresented in
|
||||
if !isPresented {
|
||||
showSidebar = false
|
||||
privateConversationModel.endConversation()
|
||||
// Scene/background and alert-presentation
|
||||
// reconciliation (Bluetooth-off, recording errors)
|
||||
// are not user requests to leave the conversation.
|
||||
// Keep the selected DM so the sheet remains live
|
||||
// when the app returns from Settings.
|
||||
if scenePhase == .active,
|
||||
!appChromeModel.showBluetoothAlert,
|
||||
!voiceRecordingVM.showAlert {
|
||||
privateConversationModel.endConversation()
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
@@ -226,7 +365,7 @@ struct ContentView: View {
|
||||
ImagePreviewView(url: url)
|
||||
}
|
||||
}
|
||||
.alert("Recording Error", isPresented: $voiceRecordingVM.showAlert, actions: {
|
||||
.alert("Recording Error", isPresented: rootVoiceAlertBinding, actions: {
|
||||
Button("common.ok", role: .cancel) {}
|
||||
if voiceRecordingVM.state == .permissionDenied {
|
||||
Button("location_channels.action.open_settings") {
|
||||
@@ -236,7 +375,7 @@ struct ContentView: View {
|
||||
}, message: {
|
||||
Text(voiceRecordingVM.state.alertMessage)
|
||||
})
|
||||
.alert("content.alert.bluetooth_required.title", isPresented: $appChromeModel.showBluetoothAlert) {
|
||||
.alert("content.alert.bluetooth_required.title", isPresented: rootBluetoothAlertBinding) {
|
||||
Button("content.alert.bluetooth_required.settings") {
|
||||
SystemSettings.bluetooth.open()
|
||||
}
|
||||
|
||||
@@ -39,7 +39,7 @@ struct BLEServiceCoreTests {
|
||||
ble._test_handlePacket(packet, fromPeerID: sender, signingPublicKey: signingKey)
|
||||
let receivedDuplicate = await TestHelpers.waitUntil(
|
||||
{ delegate.publicMessagesSnapshot().count > 1 },
|
||||
timeout: TestConstants.shortTimeout
|
||||
timeout: TestConstants.negativeWaitWindow
|
||||
)
|
||||
#expect(!receivedDuplicate)
|
||||
|
||||
@@ -117,7 +117,7 @@ struct BLEServiceCoreTests {
|
||||
|
||||
let unsignedRelayed = await TestHelpers.waitUntil(
|
||||
{ outbound.count(ofType: .leave) > 0 },
|
||||
timeout: TestConstants.shortTimeout
|
||||
timeout: TestConstants.negativeWaitWindow
|
||||
)
|
||||
#expect(!unsignedRelayed)
|
||||
#expect(ble.currentPeerSnapshots().contains { $0.peerID == alicePeerID })
|
||||
@@ -133,7 +133,7 @@ struct BLEServiceCoreTests {
|
||||
|
||||
let badSignatureRelayed = await TestHelpers.waitUntil(
|
||||
{ outbound.count(ofType: .leave) > 0 },
|
||||
timeout: TestConstants.shortTimeout
|
||||
timeout: TestConstants.negativeWaitWindow
|
||||
)
|
||||
#expect(!badSignatureRelayed)
|
||||
#expect(ble.currentPeerSnapshots().contains { $0.peerID == alicePeerID })
|
||||
@@ -1209,7 +1209,7 @@ struct BLEServiceCoreTests {
|
||||
let didObservePanicClosure = await withCheckedContinuation { continuation in
|
||||
DispatchQueue.global(qos: .userInitiated).async {
|
||||
let didObserveClosure = panicIngressObserver.waitUntilClosed(
|
||||
timeout: TestConstants.defaultTimeout
|
||||
timeout: TestConstants.settleTimeout
|
||||
)
|
||||
gate.release()
|
||||
continuation.resume(returning: didObserveClosure)
|
||||
@@ -1340,7 +1340,7 @@ struct BLEServiceCoreTests {
|
||||
// rotated sender IDs never bought a sixth response.
|
||||
let exceededBudget = await TestHelpers.waitUntil(
|
||||
{ outbound.count(ofType: .pong) > budget },
|
||||
timeout: TestConstants.shortTimeout
|
||||
timeout: TestConstants.negativeWaitWindow
|
||||
)
|
||||
#expect(!exceededBudget)
|
||||
#expect(outbound.count(ofType: .pong) == budget)
|
||||
|
||||
@@ -176,6 +176,9 @@ private final class MockChatPrivateConversationContext: ChatPrivateConversationC
|
||||
private(set) var geoPrivateMessages: [(content: String, recipientHex: String, messageID: String)] = []
|
||||
private(set) var geoDeliveryAcks: [(messageID: String, recipientHex: String)] = []
|
||||
private(set) var geoReadReceipts: [(messageID: String, recipientHex: String)] = []
|
||||
var queuedMessageIDsByPeerID: [PeerID: Set<String>] = [:]
|
||||
private(set) var deliveryAckAttempts: [(messageID: String, peerIDs: [PeerID])] = []
|
||||
private(set) var deliveredMessageIDs: [String] = []
|
||||
|
||||
func routePrivateMessage(_ content: String, to peerID: PeerID, recipientNickname: String, messageID: String) {
|
||||
routedPrivateMessages.append((content, peerID, messageID))
|
||||
@@ -187,6 +190,22 @@ private final class MockChatPrivateConversationContext: ChatPrivateConversationC
|
||||
return routeReadReceiptResult
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
func markMessageDelivered(_ messageID: String, for peerIDs: [PeerID]) -> Bool {
|
||||
deliveryAckAttempts.append((messageID, peerIDs))
|
||||
var cleared = false
|
||||
for peerID in Set(peerIDs) {
|
||||
guard var queued = queuedMessageIDsByPeerID[peerID],
|
||||
queued.remove(messageID) != nil else { continue }
|
||||
queuedMessageIDsByPeerID[peerID] = queued.isEmpty ? nil : queued
|
||||
cleared = true
|
||||
}
|
||||
if cleared {
|
||||
deliveredMessageIDs.append(messageID)
|
||||
}
|
||||
return cleared
|
||||
}
|
||||
|
||||
func sendMeshReadReceipt(_ receipt: ReadReceipt, to peerID: PeerID) {
|
||||
meshReadReceipts.append((receipt.originalMessageID, peerID))
|
||||
}
|
||||
@@ -370,6 +389,66 @@ struct ChatPrivateConversationCoordinatorContextTests {
|
||||
convKey: convKey
|
||||
)
|
||||
#expect(context.notifyUIChangedCount == 2)
|
||||
#expect(context.deliveryAckAttempts.isEmpty)
|
||||
#expect(context.deliveredMessageIDs.isEmpty)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func accountDMAcks_findShortIDMessageAndHandConversationToStable() async {
|
||||
let context = MockChatPrivateConversationContext()
|
||||
let coordinator = ChatPrivateConversationCoordinator(context: context)
|
||||
let noiseKey = Data(repeating: 0xD5, count: 32)
|
||||
let stablePeerID = PeerID(hexData: noiseKey)
|
||||
let shortPeerID = stablePeerID.toShort()
|
||||
let senderPubkey = "feedface00112233"
|
||||
context.displayNamesByPubkey[senderPubkey] = "alice"
|
||||
context.selectedPrivateChatPeer = shortPeerID
|
||||
context.privateChats[shortPeerID] = [
|
||||
makeIncomingMessage(id: "mine-short-1", sender: "me"),
|
||||
makeIncomingMessage(id: "mine-short-2", sender: "me")
|
||||
]
|
||||
context.queuedMessageIDsByPeerID[shortPeerID] = ["mine-short-1", "mine-short-2"]
|
||||
|
||||
coordinator.handleDelivered(
|
||||
NoisePayload(type: .delivered, data: Data("mine-short-1".utf8)),
|
||||
senderPubkey: senderPubkey,
|
||||
convKey: stablePeerID
|
||||
)
|
||||
coordinator.handleReadReceipt(
|
||||
NoisePayload(type: .readReceipt, data: Data("mine-short-2".utf8)),
|
||||
senderPubkey: senderPubkey,
|
||||
convKey: stablePeerID
|
||||
)
|
||||
|
||||
#expect(context.privateChats[shortPeerID] == nil)
|
||||
#expect(isDelivered(context.privateChats[stablePeerID]?.first?.deliveryStatus, to: "alice"))
|
||||
#expect(isRead(context.privateChats[stablePeerID]?.last?.deliveryStatus, by: "alice"))
|
||||
#expect(context.selectedPrivateChatPeer == stablePeerID)
|
||||
#expect(context.deliveredMessageIDs == ["mine-short-1", "mine-short-2"])
|
||||
#expect(context.notifyUIChangedCount == 2)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func accountDMAck_doesNotTouchAnUnrelatedConversationWithTheSameMessageID() async {
|
||||
let context = MockChatPrivateConversationContext()
|
||||
let coordinator = ChatPrivateConversationCoordinator(context: context)
|
||||
let stablePeerID = PeerID(hexData: Data(repeating: 0xC1, count: 32))
|
||||
let unrelatedPeerID = PeerID(str: "1111222233334444")
|
||||
context.privateChats[unrelatedPeerID] = [
|
||||
makeIncomingMessage(id: "collision", sender: "me")
|
||||
]
|
||||
context.queuedMessageIDsByPeerID[unrelatedPeerID] = ["collision"]
|
||||
|
||||
coordinator.handleDelivered(
|
||||
NoisePayload(type: .delivered, data: Data("collision".utf8)),
|
||||
senderPubkey: "feedface00112233",
|
||||
convKey: stablePeerID
|
||||
)
|
||||
|
||||
#expect(isDelivered(context.privateChats[unrelatedPeerID]?.first?.deliveryStatus, to: "me"))
|
||||
#expect(context.deliveredMessageIDs.isEmpty)
|
||||
#expect(context.queuedMessageIDsByPeerID[unrelatedPeerID] == ["collision"])
|
||||
#expect(context.notifyUIChangedCount == 0)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
@@ -412,6 +491,180 @@ struct ChatPrivateConversationCoordinatorContextTests {
|
||||
#expect(context.privateChats[convKey]?.count == 1)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func accountDM_handsOpenShortIDConversationToStableWhenOffline() async {
|
||||
let context = MockChatPrivateConversationContext()
|
||||
let coordinator = ChatPrivateConversationCoordinator(context: context)
|
||||
let noiseKey = Data(repeating: 0xA7, count: 32)
|
||||
let stablePeerID = PeerID(hexData: noiseKey)
|
||||
let shortPeerID = stablePeerID.toShort()
|
||||
let senderPubkey = "feedface00112233"
|
||||
let now = Date()
|
||||
context.displayNamesByPubkey[senderPubkey] = "bob"
|
||||
context.selectedPrivateChatPeer = shortPeerID
|
||||
context.privateChats[shortPeerID] = [
|
||||
makeIncomingMessage(
|
||||
id: "short-history",
|
||||
sender: "me",
|
||||
timestamp: now.addingTimeInterval(-30),
|
||||
senderPeerID: context.myPeerID
|
||||
),
|
||||
makeIncomingMessage(
|
||||
id: "short-inbound",
|
||||
sender: "bob",
|
||||
timestamp: now.addingTimeInterval(-25),
|
||||
senderPeerID: shortPeerID
|
||||
)
|
||||
]
|
||||
context.privateChats[stablePeerID] = [
|
||||
makeIncomingMessage(
|
||||
id: "stable-history",
|
||||
sender: "bob",
|
||||
timestamp: now.addingTimeInterval(-20),
|
||||
senderPeerID: stablePeerID
|
||||
)
|
||||
]
|
||||
let payloadData = PrivateMessagePacket(messageID: "account-live-1", content: "live reply").encode()!
|
||||
|
||||
coordinator.handlePrivateMessage(
|
||||
NoisePayload(type: .privateMessage, data: payloadData),
|
||||
senderPubkey: senderPubkey,
|
||||
convKey: stablePeerID,
|
||||
id: MockChatPrivateConversationContext.dummyIdentity,
|
||||
messageTimestamp: now
|
||||
)
|
||||
|
||||
#expect(context.privateChats[shortPeerID] == nil)
|
||||
#expect(context.privateChats[stablePeerID]?.map(\.id) == [
|
||||
"short-history",
|
||||
"short-inbound",
|
||||
"stable-history",
|
||||
"account-live-1"
|
||||
])
|
||||
#expect(context.privateChats[stablePeerID]?[1].senderPeerID == stablePeerID)
|
||||
#expect(context.privateChats[stablePeerID]?.last?.senderPeerID == stablePeerID)
|
||||
#expect(context.migratedChats.contains(where: { $0.from == shortPeerID && $0.to == stablePeerID }))
|
||||
#expect(context.selectedPrivateChatPeer == stablePeerID)
|
||||
#expect(context.geoReadReceipts.map(\.messageID) == ["account-live-1"])
|
||||
#expect(context.unreadPrivateMessages.isEmpty)
|
||||
#expect(context.notifyUIChangedCount == 1)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func accountDM_aliasMergePreservesTheCanonicalDestinationCopy() async {
|
||||
let context = MockChatPrivateConversationContext()
|
||||
let coordinator = ChatPrivateConversationCoordinator(context: context)
|
||||
let noiseKey = Data(repeating: 0xA8, count: 32)
|
||||
let stablePeerID = PeerID(hexData: noiseKey)
|
||||
let shortPeerID = stablePeerID.toShort()
|
||||
let senderPubkey = "feedface00112233"
|
||||
let olderSource = makeIncomingMessage(
|
||||
id: "duplicate-history",
|
||||
sender: "bob",
|
||||
content: "older source copy",
|
||||
senderPeerID: shortPeerID
|
||||
)
|
||||
olderSource.deliveryStatus = .delivered(to: "me", at: Date(timeIntervalSince1970: 10))
|
||||
let newerDestination = makeIncomingMessage(
|
||||
id: "duplicate-history",
|
||||
sender: "bob",
|
||||
content: "newer destination copy",
|
||||
senderPeerID: shortPeerID
|
||||
)
|
||||
newerDestination.deliveryStatus = .read(by: "me", at: Date(timeIntervalSince1970: 20))
|
||||
context.privateChats[shortPeerID] = [olderSource]
|
||||
context.privateChats[stablePeerID] = [newerDestination]
|
||||
context.displayNamesByPubkey[senderPubkey] = "bob"
|
||||
let payloadData = PrivateMessagePacket(messageID: "after-merge", content: "new reply").encode()!
|
||||
|
||||
coordinator.handlePrivateMessage(
|
||||
NoisePayload(type: .privateMessage, data: payloadData),
|
||||
senderPubkey: senderPubkey,
|
||||
convKey: stablePeerID,
|
||||
id: MockChatPrivateConversationContext.dummyIdentity,
|
||||
messageTimestamp: Date()
|
||||
)
|
||||
|
||||
let merged = context.privateChats[stablePeerID]?.first
|
||||
#expect(context.privateChats[shortPeerID] == nil)
|
||||
#expect(merged?.content == "newer destination copy")
|
||||
#expect(isRead(merged?.deliveryStatus, by: "me"))
|
||||
#expect(merged?.senderPeerID == stablePeerID)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func accountDM_keepsTheConnectedShortIDConversationCanonical() async {
|
||||
let context = MockChatPrivateConversationContext()
|
||||
let coordinator = ChatPrivateConversationCoordinator(context: context)
|
||||
let noiseKey = Data(repeating: 0xB8, count: 32)
|
||||
let stablePeerID = PeerID(hexData: noiseKey)
|
||||
let shortPeerID = stablePeerID.toShort()
|
||||
let senderPubkey = "feedface00112233"
|
||||
context.connectedPeers = [shortPeerID]
|
||||
context.selectedPrivateChatPeer = stablePeerID
|
||||
context.displayNamesByPubkey[senderPubkey] = "bob"
|
||||
context.privateChats[stablePeerID] = [
|
||||
makeIncomingMessage(id: "stable-history", senderPeerID: stablePeerID)
|
||||
]
|
||||
let payloadData = PrivateMessagePacket(messageID: "connected-live-1", content: "still nearby").encode()!
|
||||
|
||||
coordinator.handlePrivateMessage(
|
||||
NoisePayload(type: .privateMessage, data: payloadData),
|
||||
senderPubkey: senderPubkey,
|
||||
convKey: stablePeerID,
|
||||
id: MockChatPrivateConversationContext.dummyIdentity,
|
||||
messageTimestamp: Date()
|
||||
)
|
||||
|
||||
#expect(context.privateChats[stablePeerID] == nil)
|
||||
#expect(context.privateChats[shortPeerID]?.map(\.id) == ["stable-history", "connected-live-1"])
|
||||
#expect(context.privateChats[shortPeerID]?.first?.senderPeerID == shortPeerID)
|
||||
#expect(context.privateChats[shortPeerID]?.last?.senderPeerID == shortPeerID)
|
||||
#expect(context.selectedPrivateChatPeer == shortPeerID)
|
||||
#expect(context.geoReadReceipts.map(\.messageID) == ["connected-live-1"])
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func accountDM_duplicateDowngradeAckStillClearsTheRetainedOutbox() async {
|
||||
let context = MockChatPrivateConversationContext()
|
||||
let coordinator = ChatPrivateConversationCoordinator(context: context)
|
||||
let stablePeerID = PeerID(hexData: Data(repeating: 0xE2, count: 32))
|
||||
let message = makeIncomingMessage(id: "already-read", sender: "me")
|
||||
message.deliveryStatus = .read(by: "bob", at: Date())
|
||||
context.privateChats[stablePeerID] = [message]
|
||||
context.queuedMessageIDsByPeerID[stablePeerID] = ["already-read"]
|
||||
|
||||
coordinator.handleDelivered(
|
||||
NoisePayload(type: .delivered, data: Data("already-read".utf8)),
|
||||
senderPubkey: "feedface00112233",
|
||||
convKey: stablePeerID
|
||||
)
|
||||
|
||||
#expect(isRead(context.privateChats[stablePeerID]?.first?.deliveryStatus, by: "bob"))
|
||||
#expect(context.deliveredMessageIDs == ["already-read"])
|
||||
#expect(context.notifyUIChangedCount == 0)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func accountDMAck_clearsRetainedMessageAfterConversationWasRemoved() async {
|
||||
let context = MockChatPrivateConversationContext()
|
||||
let coordinator = ChatPrivateConversationCoordinator(context: context)
|
||||
let stablePeerID = PeerID(hexData: Data(repeating: 0xE3, count: 32))
|
||||
let shortPeerID = stablePeerID.toShort()
|
||||
context.queuedMessageIDsByPeerID[shortPeerID] = ["cleared-bubble"]
|
||||
|
||||
coordinator.handleDelivered(
|
||||
NoisePayload(type: .delivered, data: Data("cleared-bubble".utf8)),
|
||||
senderPubkey: "feedface00112233",
|
||||
convKey: stablePeerID
|
||||
)
|
||||
|
||||
#expect(context.privateChats.isEmpty)
|
||||
#expect(context.queuedMessageIDsByPeerID[shortPeerID] == nil)
|
||||
#expect(context.deliveredMessageIDs == ["cleared-bubble"])
|
||||
#expect(context.notifyUIChangedCount == 0)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func handleViewingThisChat_clearsUnreadAndSendsRoutedReadReceiptOnce() async {
|
||||
let context = MockChatPrivateConversationContext()
|
||||
|
||||
@@ -79,12 +79,17 @@ private final class MockChatPublicConversationContext: ChatPublicConversationCon
|
||||
}
|
||||
|
||||
private(set) var clearedConversations: [ConversationID] = []
|
||||
private(set) var archivePurgeCount = 0
|
||||
|
||||
func clearPublicConversation(_ conversationID: ConversationID) {
|
||||
clearedConversations.append(conversationID)
|
||||
conversations[conversationID] = []
|
||||
}
|
||||
|
||||
func purgeArchivedPublicMessages() {
|
||||
archivePurgeCount += 1
|
||||
}
|
||||
|
||||
func queueGeohashSystemMessage(_ content: String) {
|
||||
queuedGeohashSystemMessages.append(content)
|
||||
}
|
||||
@@ -345,6 +350,35 @@ struct ChatPublicConversationCoordinatorContextTests {
|
||||
#expect(context.enqueuedMessages.first?.conversationID == .geohash(geohash))
|
||||
}
|
||||
|
||||
/// `/clear` on the mesh timeline used to only record a watermark, leaving
|
||||
/// the archive on disk for up to its freshness window — so someone who
|
||||
/// cleared before a police stop had deleted nothing. It must now erase the
|
||||
/// archive behind the timeline.
|
||||
@Test @MainActor
|
||||
func clearCurrentPublicTimeline_onMesh_erasesTheArchive() async {
|
||||
let context = MockChatPublicConversationContext()
|
||||
let coordinator = ChatPublicConversationCoordinator(context: context)
|
||||
context.activeChannel = .mesh
|
||||
|
||||
coordinator.clearCurrentPublicTimeline()
|
||||
|
||||
#expect(context.clearedConversations == [.mesh])
|
||||
#expect(context.archivePurgeCount == 1)
|
||||
}
|
||||
|
||||
/// Geohash timelines are Nostr-backed and carry no mesh gossip archive, so
|
||||
/// clearing one must not reach for it.
|
||||
@Test @MainActor
|
||||
func clearCurrentPublicTimeline_onGeohash_leavesTheArchiveAlone() async {
|
||||
let context = MockChatPublicConversationContext()
|
||||
let coordinator = ChatPublicConversationCoordinator(context: context)
|
||||
context.activeChannel = .location(GeohashChannel(level: .city, geohash: "u4pruy"))
|
||||
|
||||
coordinator.clearCurrentPublicTimeline()
|
||||
|
||||
#expect(context.archivePurgeCount == 0)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func blockGeohashUser_purgesMessagesMappingsAndPrivateChats() async {
|
||||
let context = MockChatPublicConversationContext()
|
||||
|
||||
@@ -133,11 +133,17 @@ private final class MockChatTransportEventContext: ChatTransportEventContext {
|
||||
// Delivery status
|
||||
var applyMessageDeliveryStatusResult = true
|
||||
var deliveryStatusesByMessageID: [String: DeliveryStatus] = [:]
|
||||
private(set) var appliedDeliveryStatuses: [(messageID: String, status: DeliveryStatus)] = []
|
||||
private(set) var appliedDeliveryStatuses: [
|
||||
(messageID: String, status: DeliveryStatus, peerIDAliases: Set<PeerID>)
|
||||
] = []
|
||||
|
||||
@discardableResult
|
||||
func applyMessageDeliveryStatus(_ messageID: String, status: DeliveryStatus) -> Bool {
|
||||
appliedDeliveryStatuses.append((messageID, status))
|
||||
func applyAcknowledgedMessageDeliveryStatus(
|
||||
_ messageID: String,
|
||||
status: DeliveryStatus,
|
||||
from peerIDAliases: Set<PeerID>
|
||||
) -> Bool {
|
||||
appliedDeliveryStatuses.append((messageID, status, peerIDAliases))
|
||||
return applyMessageDeliveryStatusResult
|
||||
}
|
||||
|
||||
@@ -417,6 +423,10 @@ struct ChatTransportEventCoordinatorContextTests {
|
||||
let peerID = PeerID(str: "99aabbccddeeff00")
|
||||
let noiseKey = Data(repeating: 0x44, count: 32)
|
||||
context.peersByID[peerID] = BitchatPeer(peerID: peerID, noisePublicKey: noiseKey, nickname: "alice")
|
||||
let stablePeerID = PeerID(hexData: noiseKey)
|
||||
let staleStablePeerID = PeerID(hexData: Data(repeating: 0x55, count: 32))
|
||||
context.cacheStablePeerID(staleStablePeerID, for: peerID)
|
||||
context.noiseSessionKeysByPeerID[peerID] = noiseKey
|
||||
|
||||
// Inbound private message: decoded, handled, and delivery-acked.
|
||||
let packet = PrivateMessagePacket(messageID: "pm-1", content: "hi there")
|
||||
@@ -438,6 +448,8 @@ struct ChatTransportEventCoordinatorContextTests {
|
||||
await drainMainActorTasks()
|
||||
#expect(context.appliedDeliveryStatuses.count == 2)
|
||||
#expect(context.appliedDeliveryStatuses[0].messageID == "m-1")
|
||||
#expect(context.appliedDeliveryStatuses[0].peerIDAliases == [peerID, stablePeerID])
|
||||
#expect(!context.appliedDeliveryStatuses[0].peerIDAliases.contains(staleStablePeerID))
|
||||
if case .delivered(let to, _) = context.appliedDeliveryStatuses[0].status {
|
||||
#expect(to == "alice")
|
||||
} else {
|
||||
|
||||
@@ -98,6 +98,7 @@ private final class MockChatVerificationContext: ChatVerificationContext {
|
||||
private(set) var installedCallbacks: (onPeerAuthenticated: (PeerID, String) -> Void, onHandshakeRequired: (PeerID) -> Void)?
|
||||
private(set) var triggeredHandshakes: [PeerID] = []
|
||||
private(set) var privateMediaAuthenticatedPeers: [PeerID] = []
|
||||
private(set) var securePrivateMessageRetryAliases: [[PeerID]] = []
|
||||
private(set) var sentChallenges: [(peerID: PeerID, noiseKeyHex: String, nonceA: Data)] = []
|
||||
private(set) var sentResponses: [(peerID: PeerID, noiseKeyHex: String, nonceA: Data)] = []
|
||||
|
||||
@@ -118,6 +119,10 @@ private final class MockChatVerificationContext: ChatVerificationContext {
|
||||
privateMediaAuthenticatedPeers.append(peerID)
|
||||
}
|
||||
|
||||
func retrySecurePrivateMessagesAfterAuthentication(for peerIDAliases: [PeerID]) {
|
||||
securePrivateMessageRetryAliases.append(peerIDAliases)
|
||||
}
|
||||
|
||||
func sendVerifyChallenge(to peerID: PeerID, noiseKeyHex: String, nonceA: Data) {
|
||||
sentChallenges.append((peerID, noiseKeyHex, nonceA))
|
||||
}
|
||||
@@ -269,6 +274,10 @@ struct ChatVerificationCoordinatorContextTests {
|
||||
let peerID = PeerID(str: "1122334455667788")
|
||||
let noiseKey = Data(repeating: 0x33, count: 32)
|
||||
context.noiseSessionKeysByPeerID[peerID] = noiseKey
|
||||
context.cacheStablePeerID(
|
||||
PeerID(hexData: Data(repeating: 0x44, count: 32)),
|
||||
for: peerID
|
||||
)
|
||||
context.verifiedFingerprints = ["fp-verified"]
|
||||
|
||||
coordinator.setupNoiseCallbacks()
|
||||
@@ -279,9 +288,11 @@ struct ChatVerificationCoordinatorContextTests {
|
||||
callbacks?.onPeerAuthenticated(peerID, "fp-verified")
|
||||
await waitForMainQueue()
|
||||
#expect(context.encryptionStatuses[peerID] == .noiseVerified)
|
||||
#expect(context.stablePeerIDCache[peerID] == PeerID(hexData: noiseKey))
|
||||
let stablePeerID = PeerID(hexData: noiseKey)
|
||||
#expect(context.stablePeerIDCache[peerID] == stablePeerID)
|
||||
#expect(context.invalidatedEncryptionCachePeers.contains(peerID))
|
||||
#expect(context.privateMediaAuthenticatedPeers == [peerID])
|
||||
#expect(context.securePrivateMessageRetryAliases == [[peerID, stablePeerID]])
|
||||
|
||||
// Handshake required -> handshaking status.
|
||||
callbacks?.onHandshakeRequired(peerID)
|
||||
|
||||
@@ -13,8 +13,11 @@ import BitFoundation
|
||||
// MARK: - Test Helpers
|
||||
|
||||
@MainActor
|
||||
private func makeTestableViewModel() -> (viewModel: ChatViewModel, transport: MockTransport) {
|
||||
let keychain = MockKeychain()
|
||||
private func makeTestableViewModel(
|
||||
keychain injectedKeychain: MockKeychain? = nil,
|
||||
outboxStore: MessageOutboxStore? = nil
|
||||
) -> (viewModel: ChatViewModel, transport: MockTransport) {
|
||||
let keychain = injectedKeychain ?? MockKeychain()
|
||||
let keychainHelper = MockKeychainHelper()
|
||||
let idBridge = NostrIdentityBridge(keychain: keychainHelper)
|
||||
let identityManager = MockIdentityManager(keychain)
|
||||
@@ -24,7 +27,8 @@ private func makeTestableViewModel() -> (viewModel: ChatViewModel, transport: Mo
|
||||
keychain: keychain,
|
||||
idBridge: idBridge,
|
||||
identityManager: identityManager,
|
||||
transport: transport
|
||||
transport: transport,
|
||||
outboxStore: outboxStore
|
||||
)
|
||||
|
||||
return (viewModel, transport)
|
||||
@@ -298,6 +302,137 @@ struct ChatViewModelDeliveryStatusTests {
|
||||
}())
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func authenticatedNoiseAckCannotClearAnotherPeersRetryState() async {
|
||||
let (viewModel, transport) = makeTestableViewModel()
|
||||
let intendedPeer = PeerID(str: "0102030405060708")
|
||||
let otherPeer = PeerID(str: "1112131415161718")
|
||||
let messageID = "noise-peer-bound-ack"
|
||||
|
||||
viewModel.seedPrivateChat(
|
||||
[
|
||||
BitchatMessage(
|
||||
id: messageID,
|
||||
sender: viewModel.nickname,
|
||||
content: "Keep retrying",
|
||||
timestamp: Date(),
|
||||
isRelay: false,
|
||||
isPrivate: true,
|
||||
recipientNickname: "Intended",
|
||||
senderPeerID: viewModel.myPeerID,
|
||||
deliveryStatus: .sent
|
||||
)
|
||||
],
|
||||
for: intendedPeer
|
||||
)
|
||||
transport.reachablePeers.insert(intendedPeer)
|
||||
viewModel.messageRouter.sendPrivate(
|
||||
"Keep retrying",
|
||||
to: intendedPeer,
|
||||
recipientNickname: "Intended",
|
||||
messageID: messageID
|
||||
)
|
||||
#expect(transport.sentPrivateMessages.count == 1)
|
||||
|
||||
// This models a decrypted Noise receipt: the transport-authenticated
|
||||
// peer is authoritative, not the attacker-controlled message ID.
|
||||
viewModel.didReceiveNoisePayload(
|
||||
from: otherPeer,
|
||||
type: .delivered,
|
||||
payload: Data(messageID.utf8),
|
||||
timestamp: Date()
|
||||
)
|
||||
for _ in 0..<10 { await Task.yield() }
|
||||
|
||||
#expect(isSent(viewModel.conversations.deliveryStatus(forMessageID: messageID)))
|
||||
viewModel.messageRouter.flushOutbox(for: intendedPeer)
|
||||
#expect(transport.sentPrivateMessages.count == 2)
|
||||
|
||||
viewModel.didReceiveNoisePayload(
|
||||
from: intendedPeer,
|
||||
type: .delivered,
|
||||
payload: Data(messageID.utf8),
|
||||
timestamp: Date()
|
||||
)
|
||||
for _ in 0..<10 { await Task.yield() }
|
||||
|
||||
#expect(isDelivered(viewModel.conversations.deliveryStatus(forMessageID: messageID)))
|
||||
viewModel.messageRouter.flushOutbox(for: intendedPeer)
|
||||
#expect(transport.sentPrivateMessages.count == 2)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func authenticatedNoiseAckClearsOnlyIntendedPeersPrivateMediaRetry() async throws {
|
||||
let (viewModel, transport) = makeTestableViewModel()
|
||||
let intendedPeer = PeerID(str: "0102030405060708")
|
||||
let otherPeer = PeerID(str: "1112131415161718")
|
||||
let fileName = "voice_0011223344556677.m4a"
|
||||
let content = Data("voice".utf8)
|
||||
|
||||
transport.privateMediaPolicies[intendedPeer] = .encrypted
|
||||
transport.privateMediaReceiptSessionGenerations[intendedPeer] = UUID()
|
||||
viewModel.selectedPrivateChatPeer = intendedPeer
|
||||
let coordinator = ChatMediaTransferCoordinator(
|
||||
context: viewModel,
|
||||
prepareVoiceNotePacket: { _ in
|
||||
BitchatFilePacket(
|
||||
fileName: fileName,
|
||||
fileSize: UInt64(content.count),
|
||||
mimeType: "audio/mp4",
|
||||
content: content
|
||||
)
|
||||
},
|
||||
transferIDFactory: { "\($0)-receipt-ack" }
|
||||
)
|
||||
viewModel.mediaTransferCoordinator = coordinator
|
||||
|
||||
let directory = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(
|
||||
"scoped-media-ack-\(UUID().uuidString)",
|
||||
isDirectory: true
|
||||
)
|
||||
try FileManager.default.createDirectory(
|
||||
at: directory,
|
||||
withIntermediateDirectories: true
|
||||
)
|
||||
let sourceURL = directory.appendingPathComponent(fileName)
|
||||
try content.write(to: sourceURL)
|
||||
defer { try? FileManager.default.removeItem(at: directory) }
|
||||
|
||||
coordinator.sendVoiceNote(at: sourceURL)
|
||||
#expect(await TestHelpers.waitUntil(
|
||||
{
|
||||
transport.sentPrivateFiles.count == 1
|
||||
&& coordinator.retainedReconnectRetryCount == 1
|
||||
},
|
||||
timeout: TestConstants.longTimeout
|
||||
))
|
||||
let messageID = try #require(
|
||||
viewModel.privateChats[intendedPeer]?.first?.id
|
||||
)
|
||||
let transferID = try #require(
|
||||
transport.sentPrivateFiles.first?.transferID
|
||||
)
|
||||
|
||||
#expect(!viewModel.deliveryCoordinator
|
||||
.updateAcknowledgedMessageDeliveryStatus(
|
||||
messageID,
|
||||
status: .delivered(to: "Other", at: Date()),
|
||||
from: [otherPeer]
|
||||
))
|
||||
#expect(coordinator.retainedReconnectRetryCount == 1)
|
||||
#expect(transport.cancelledTransfers.isEmpty)
|
||||
|
||||
#expect(viewModel.deliveryCoordinator
|
||||
.updateAcknowledgedMessageDeliveryStatus(
|
||||
messageID,
|
||||
status: .delivered(to: "Intended", at: Date()),
|
||||
from: [intendedPeer]
|
||||
))
|
||||
#expect(coordinator.retainedReconnectRetryCount == 0)
|
||||
#expect(transport.cancelledTransfers == [transferID])
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func cleanupOldReadReceipts_removesReceiptIDsWithoutMessages() async {
|
||||
let (viewModel, transport) = makeTestableViewModel()
|
||||
@@ -323,6 +458,65 @@ struct ChatViewModelDeliveryStatusTests {
|
||||
#expect(viewModel.sentReadReceipts == ["keep-receipt"])
|
||||
}
|
||||
|
||||
// MARK: - Relaunch-Restored Outbox Tests
|
||||
|
||||
@Test @MainActor
|
||||
func deliveryAckAfterRelaunchClearsRestoredOutboxWithoutConversation() async {
|
||||
// Force-quit → relaunch: the durable outbox restores the retained DM,
|
||||
// but the in-memory conversation store starts empty. The delivery ack
|
||||
// must still clear the router's retained copy — gating it on the
|
||||
// conversation lookup would leave the entry re-sending on every
|
||||
// flush/auth event until the attempt cap marks it failed despite
|
||||
// delivery.
|
||||
let fileURL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("relaunch-ack-\(UUID().uuidString).sealed")
|
||||
defer { try? FileManager.default.removeItem(at: fileURL) }
|
||||
let keychain = MockKeychain()
|
||||
let peerID = PeerID(str: "0102030405060708")
|
||||
let messageID = "relaunch-retained-dm"
|
||||
|
||||
// Pre-quit state: one retained private message on disk.
|
||||
MessageOutboxStore(keychain: keychain, fileURL: fileURL).save([
|
||||
peerID: [MessageOutboxStore.QueuedMessage(
|
||||
content: "Sent before force-quit",
|
||||
nickname: "Peer",
|
||||
messageID: messageID,
|
||||
timestamp: Date()
|
||||
)]
|
||||
])
|
||||
|
||||
// Relaunch: fresh view model over the same durable store.
|
||||
let (viewModel, transport) = makeTestableViewModel(
|
||||
keychain: keychain,
|
||||
outboxStore: MessageOutboxStore(keychain: keychain, fileURL: fileURL)
|
||||
)
|
||||
#expect(viewModel.privateChats[peerID] == nil)
|
||||
|
||||
// The peer's delivery ack arrives with no conversation in the store.
|
||||
// No UI transition is possible (and none must crash), but the durable
|
||||
// retry state has to clear.
|
||||
let didUpdate = viewModel.deliveryCoordinator
|
||||
.updateAcknowledgedMessageDeliveryStatus(
|
||||
messageID,
|
||||
status: .delivered(to: "Peer", at: Date()),
|
||||
from: [peerID]
|
||||
)
|
||||
#expect(!didUpdate)
|
||||
#expect(viewModel.privateChats[peerID] == nil)
|
||||
|
||||
// Neither a flush nor a replacement-handshake auth event may re-send
|
||||
// the already-delivered message.
|
||||
transport.connectedPeers.insert(peerID)
|
||||
transport.securePeers = [peerID]
|
||||
viewModel.messageRouter.flushOutbox(for: peerID)
|
||||
viewModel.messageRouter.retrySecurePrivateMessagesAfterAuthentication(for: [peerID])
|
||||
#expect(transport.sentPrivateMessages.isEmpty)
|
||||
|
||||
// The clear reached the durable snapshot: the next relaunch restores
|
||||
// nothing.
|
||||
#expect(MessageOutboxStore(keychain: keychain, fileURL: fileURL).load().isEmpty)
|
||||
}
|
||||
|
||||
// MARK: - Public Timeline Status Tests
|
||||
|
||||
@Test @MainActor
|
||||
@@ -577,12 +771,27 @@ private final class MockChatDeliveryContext: ChatDeliveryContext {
|
||||
var isStartupPhase = false
|
||||
private(set) var notifyUIChangedCount = 0
|
||||
private(set) var markedDeliveredMessageIDs: [String] = []
|
||||
private(set) var peerBoundDeliveredMessages: [(messageID: String, peerIDs: Set<PeerID>)] = []
|
||||
private(set) var confirmedMediaMessageIDs: [String] = []
|
||||
|
||||
@discardableResult
|
||||
func setDeliveryStatus(_ status: DeliveryStatus, forMessageID messageID: String) -> Bool {
|
||||
store.setDeliveryStatus(status, forMessageID: messageID)
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
func setDeliveryStatus(
|
||||
_ status: DeliveryStatus,
|
||||
forMessageID messageID: String,
|
||||
inDirectPeerAliases peerIDs: Set<PeerID>
|
||||
) -> Bool {
|
||||
store.setDeliveryStatus(
|
||||
status,
|
||||
forMessageID: messageID,
|
||||
inDirectPeerAliases: peerIDs
|
||||
)
|
||||
}
|
||||
|
||||
func deliveryStatus(forMessageID messageID: String) -> DeliveryStatus? {
|
||||
store.deliveryStatus(forMessageID: messageID)
|
||||
}
|
||||
@@ -604,6 +813,28 @@ private final class MockChatDeliveryContext: ChatDeliveryContext {
|
||||
func markMessageDelivered(_ messageID: String) {
|
||||
markedDeliveredMessageIDs.append(messageID)
|
||||
}
|
||||
|
||||
func markMessageDelivered(_ messageID: String, from peerIDs: Set<PeerID>) {
|
||||
peerBoundDeliveredMessages.append((messageID, peerIDs))
|
||||
}
|
||||
|
||||
func confirmPrivateMediaDelivery(_ messageID: String) {
|
||||
confirmedMediaMessageIDs.append(messageID)
|
||||
}
|
||||
|
||||
func isOutgoingPrivateMessage(_ messageID: String, toAny peerIDs: Set<PeerID>) -> Bool {
|
||||
peerIDs.contains { peerID in
|
||||
contextMessages(for: peerID).contains { message in
|
||||
message.id == messageID && message.senderPeerID == localPeerID
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private let localPeerID = PeerID(str: "aabbccddeeff0011")
|
||||
|
||||
private func contextMessages(for peerID: PeerID) -> [BitchatMessage] {
|
||||
store.conversationsByID[.directPeer(peerID)]?.messages ?? []
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@@ -685,7 +916,163 @@ struct ChatDeliveryCoordinatorContextTests {
|
||||
|
||||
#expect(isRead(coordinator.deliveryStatus(for: messageID)))
|
||||
#expect(context.notifyUIChangedCount == 1)
|
||||
#expect(context.markedDeliveredMessageIDs == [messageID])
|
||||
#expect(context.markedDeliveredMessageIDs.isEmpty)
|
||||
#expect(context.peerBoundDeliveredMessages.count == 1)
|
||||
#expect(context.peerBoundDeliveredMessages[0].messageID == messageID)
|
||||
#expect(context.peerBoundDeliveredMessages[0].peerIDs == [peerID])
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func authenticatedReceiptWithCollidingIDUpdatesOnlyAuthenticatedAliases() async {
|
||||
let context = MockChatDeliveryContext()
|
||||
let coordinator = ChatDeliveryCoordinator(context: context)
|
||||
let ephemeralPeerID = PeerID(str: "0102030405060708")
|
||||
let stablePeerID = PeerID(hexData: Data(repeating: 0x08, count: 32))
|
||||
let otherPeerID = PeerID(str: "1112131415161718")
|
||||
let messageID = "authenticated-receipt-collision"
|
||||
let mirroredMessage = makePrivateMessage(id: messageID, status: .sent)
|
||||
|
||||
context.store.append(mirroredMessage, to: .directPeer(ephemeralPeerID))
|
||||
context.store.append(mirroredMessage, to: .directPeer(stablePeerID))
|
||||
context.store.append(
|
||||
makePrivateMessage(id: messageID, status: .sent),
|
||||
to: .directPeer(otherPeerID)
|
||||
)
|
||||
context.store.append(makePublicMessage(id: messageID, status: .sent), to: .mesh)
|
||||
|
||||
let aliases: Set<PeerID> = [ephemeralPeerID, stablePeerID]
|
||||
let didUpdate = coordinator.updateAcknowledgedMessageDeliveryStatus(
|
||||
messageID,
|
||||
status: .delivered(to: "Peer", at: Date()),
|
||||
from: aliases
|
||||
)
|
||||
|
||||
#expect(didUpdate)
|
||||
#expect(isDelivered(
|
||||
context.store.conversation(for: .directPeer(ephemeralPeerID))
|
||||
.message(withID: messageID)?.deliveryStatus
|
||||
))
|
||||
#expect(isDelivered(
|
||||
context.store.conversation(for: .directPeer(stablePeerID))
|
||||
.message(withID: messageID)?.deliveryStatus
|
||||
))
|
||||
#expect(isSent(
|
||||
context.store.conversation(for: .directPeer(otherPeerID))
|
||||
.message(withID: messageID)?.deliveryStatus
|
||||
))
|
||||
#expect(isSent(
|
||||
context.store.conversation(for: .mesh)
|
||||
.message(withID: messageID)?.deliveryStatus
|
||||
))
|
||||
#expect(context.peerBoundDeliveredMessages.count == 1)
|
||||
#expect(context.peerBoundDeliveredMessages[0].messageID == messageID)
|
||||
#expect(context.peerBoundDeliveredMessages[0].peerIDs == aliases)
|
||||
#expect(context.notifyUIChangedCount == 1)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func authenticatedReceiptRemainsScopedAfterPeerAliasMigration() async {
|
||||
let context = MockChatDeliveryContext()
|
||||
let coordinator = ChatDeliveryCoordinator(context: context)
|
||||
let ephemeralPeerID = PeerID(str: "2122232425262728")
|
||||
let stablePeerID = PeerID(hexData: Data(repeating: 0x28, count: 32))
|
||||
let otherPeerID = PeerID(str: "3132333435363738")
|
||||
let messageID = "authenticated-receipt-after-migration"
|
||||
|
||||
context.store.append(
|
||||
makePrivateMessage(id: messageID, status: .sent),
|
||||
to: .directPeer(ephemeralPeerID)
|
||||
)
|
||||
context.store.append(
|
||||
makePrivateMessage(id: messageID, status: .sent),
|
||||
to: .directPeer(otherPeerID)
|
||||
)
|
||||
context.store.migrateConversation(
|
||||
from: .directPeer(ephemeralPeerID),
|
||||
to: .directPeer(stablePeerID)
|
||||
)
|
||||
|
||||
let didUpdate = coordinator.updateAcknowledgedMessageDeliveryStatus(
|
||||
messageID,
|
||||
status: .read(by: "Peer", at: Date()),
|
||||
from: [ephemeralPeerID, stablePeerID]
|
||||
)
|
||||
|
||||
#expect(didUpdate)
|
||||
#expect(context.store.conversationsByID[.directPeer(ephemeralPeerID)] == nil)
|
||||
#expect(isRead(
|
||||
context.store.conversation(for: .directPeer(stablePeerID))
|
||||
.message(withID: messageID)?.deliveryStatus
|
||||
))
|
||||
#expect(isSent(
|
||||
context.store.conversation(for: .directPeer(otherPeerID))
|
||||
.message(withID: messageID)?.deliveryStatus
|
||||
))
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func receiptFromWrongPeerDoesNotUpdateOrTerminalizeOutgoingMessage() async {
|
||||
let context = MockChatDeliveryContext()
|
||||
let coordinator = ChatDeliveryCoordinator(context: context)
|
||||
let intendedPeer = PeerID(str: "0102030405060708")
|
||||
let otherPeer = PeerID(str: "1112131415161718")
|
||||
let messageID = "wrong-peer-receipt"
|
||||
context.store.append(
|
||||
makePrivateMessage(id: messageID, status: .sent),
|
||||
to: .directPeer(intendedPeer)
|
||||
)
|
||||
|
||||
coordinator.didReceiveReadReceipt(
|
||||
ReadReceipt(
|
||||
originalMessageID: messageID,
|
||||
readerID: otherPeer,
|
||||
readerNickname: "Other"
|
||||
)
|
||||
)
|
||||
|
||||
#expect(isSent(coordinator.deliveryStatus(for: messageID)))
|
||||
// The router-side clear runs, but bound only to the wrong peer's own
|
||||
// aliases — a scoped no-op that cannot touch the intended peer's
|
||||
// retained copy. Status, media retry, and UI stay untouched.
|
||||
#expect(context.peerBoundDeliveredMessages.count == 1)
|
||||
#expect(context.peerBoundDeliveredMessages[0].messageID == messageID)
|
||||
#expect(context.peerBoundDeliveredMessages[0].peerIDs == [otherPeer])
|
||||
#expect(context.markedDeliveredMessageIDs.isEmpty)
|
||||
#expect(context.confirmedMediaMessageIDs.isEmpty)
|
||||
#expect(context.notifyUIChangedCount == 0)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func rejectedStaleReceiptDoesNotDowngradeStatusOrNotify() async {
|
||||
let context = MockChatDeliveryContext()
|
||||
let coordinator = ChatDeliveryCoordinator(context: context)
|
||||
let peerID = PeerID(str: "0102030405060708")
|
||||
let messageID = "stale-receipt"
|
||||
context.store.append(
|
||||
makePrivateMessage(
|
||||
id: messageID,
|
||||
status: .read(by: "Peer", at: Date())
|
||||
),
|
||||
to: .directPeer(peerID)
|
||||
)
|
||||
|
||||
let didUpdate = coordinator.updateAcknowledgedMessageDeliveryStatus(
|
||||
messageID,
|
||||
status: .delivered(to: "Peer", at: Date()),
|
||||
from: [peerID]
|
||||
)
|
||||
|
||||
#expect(!didUpdate)
|
||||
#expect(isRead(coordinator.deliveryStatus(for: messageID)))
|
||||
// The peer-scoped router clear re-runs (idempotent: the earlier read
|
||||
// receipt already emptied this peer's retained copy), but the stale
|
||||
// delivered ack must not downgrade the read status, release media, or
|
||||
// notify the UI.
|
||||
#expect(context.peerBoundDeliveredMessages.count == 1)
|
||||
#expect(context.peerBoundDeliveredMessages[0].peerIDs == [peerID])
|
||||
#expect(context.markedDeliveredMessageIDs.isEmpty)
|
||||
#expect(context.confirmedMediaMessageIDs.isEmpty)
|
||||
#expect(context.notifyUIChangedCount == 0)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
|
||||
@@ -1374,3 +1374,37 @@ private func makeImageData() throws -> Data {
|
||||
return data
|
||||
#endif
|
||||
}
|
||||
|
||||
// MARK: - Tor Extension Tests
|
||||
|
||||
struct ChatViewModelTorExtensionTests {
|
||||
|
||||
/// Turning Tor off mid-bootstrap must not read as "the network is
|
||||
/// blocking tor": `torEnforced` is a compile-time constant, so the stall
|
||||
/// handler has to consult the runtime preference before announcing.
|
||||
@Test @MainActor
|
||||
func bootstrapStall_withTorPreferenceOff_announcesNothing() async {
|
||||
let key = NetworkActivationService.torPreferenceKey
|
||||
let previous = UserDefaults.standard.object(forKey: key)
|
||||
defer {
|
||||
if let previous {
|
||||
UserDefaults.standard.set(previous, forKey: key)
|
||||
} else {
|
||||
UserDefaults.standard.removeObject(forKey: key)
|
||||
}
|
||||
}
|
||||
let (viewModel, _) = makeTestableViewModel()
|
||||
|
||||
UserDefaults.standard.set(false, forKey: key)
|
||||
viewModel.handleTorBootstrapDidStall()
|
||||
try? await Task.sleep(nanoseconds: 50_000_000)
|
||||
#expect(viewModel.torStallAnnounced == false)
|
||||
|
||||
// The same stall with the preference on (the persisted default) is
|
||||
// exactly what must still be announced.
|
||||
UserDefaults.standard.set(true, forKey: key)
|
||||
viewModel.handleTorBootstrapDidStall()
|
||||
try? await Task.sleep(nanoseconds: 50_000_000)
|
||||
#expect(viewModel.torStallAnnounced == true)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -43,14 +43,14 @@ struct ChatViewModelRefactoringTests {
|
||||
transport.simulateConnect(peerID, nickname: "alice")
|
||||
|
||||
let didResolve = await TestHelpers.waitUntil({ viewModel.getPeerIDForNickname("alice") != nil },
|
||||
timeout: TestConstants.shortTimeout)
|
||||
timeout: TestConstants.settleTimeout)
|
||||
#expect(didResolve)
|
||||
|
||||
// Action: User types /msg command
|
||||
viewModel.sendMessage("/msg @alice Hello Private World")
|
||||
|
||||
let didSend = await TestHelpers.waitUntil({ transport.sentPrivateMessages.count == 1 },
|
||||
timeout: TestConstants.shortTimeout)
|
||||
timeout: TestConstants.settleTimeout)
|
||||
#expect(didSend)
|
||||
|
||||
// Assert:
|
||||
@@ -74,7 +74,7 @@ struct ChatViewModelRefactoringTests {
|
||||
transport.simulateConnect(peerID, nickname: "troll")
|
||||
|
||||
let didResolve = await TestHelpers.waitUntil({ viewModel.getPeerIDForNickname("troll") != nil },
|
||||
timeout: TestConstants.shortTimeout)
|
||||
timeout: TestConstants.settleTimeout)
|
||||
#expect(didResolve)
|
||||
|
||||
// Action
|
||||
@@ -83,7 +83,7 @@ struct ChatViewModelRefactoringTests {
|
||||
// Assert
|
||||
// Verify identity manager was called to block "fingerprint_123"
|
||||
let didBlock = await TestHelpers.waitUntil({ identity.isBlocked(fingerprint: "fingerprint_123") },
|
||||
timeout: TestConstants.shortTimeout)
|
||||
timeout: TestConstants.settleTimeout)
|
||||
#expect(didBlock)
|
||||
}
|
||||
|
||||
@@ -114,7 +114,7 @@ struct ChatViewModelRefactoringTests {
|
||||
// Wait for async processing with proper timeout
|
||||
let found = await TestHelpers.waitUntil(
|
||||
{ viewModel.privateChats[senderID]?.first?.content == "Secret" },
|
||||
timeout: TestConstants.defaultTimeout
|
||||
timeout: TestConstants.settleTimeout
|
||||
)
|
||||
|
||||
// Assert
|
||||
@@ -140,7 +140,7 @@ struct ChatViewModelRefactoringTests {
|
||||
{
|
||||
viewModel.publicMessages(for: .mesh).contains(where: { $0.content == "Public Hi" })
|
||||
},
|
||||
timeout: TestConstants.defaultTimeout
|
||||
timeout: TestConstants.settleTimeout
|
||||
)
|
||||
|
||||
// Assert
|
||||
|
||||
@@ -321,7 +321,7 @@ struct ChatViewModelCommandTests {
|
||||
transport.simulateConnect(peerID, nickname: "Alice")
|
||||
let resolved = await TestHelpers.waitUntil({
|
||||
viewModel.getPeerIDForNickname("Alice") == peerID
|
||||
}, timeout: TestConstants.defaultTimeout)
|
||||
}, timeout: TestConstants.negativeWaitWindow)
|
||||
#expect(resolved)
|
||||
|
||||
viewModel.handleCommand("/msg Alice")
|
||||
@@ -422,7 +422,7 @@ struct ChatViewModelServiceLifecycleTests {
|
||||
transport.sentReadReceipts.contains {
|
||||
$0.peerID == peerID && $0.receipt.originalMessageID == "read-1"
|
||||
}
|
||||
}, timeout: TestConstants.defaultTimeout)
|
||||
}, timeout: TestConstants.negativeWaitWindow)
|
||||
|
||||
#expect(sentReadReceipt)
|
||||
#expect(!viewModel.unreadPrivateMessages.contains(peerID))
|
||||
@@ -506,7 +506,7 @@ struct ChatViewModelReceivingTests {
|
||||
|
||||
let found = await TestHelpers.waitUntil({
|
||||
viewModel.publicMessages(for: .mesh).contains { $0.content == "Public hello from Bob" }
|
||||
}, timeout: TestConstants.defaultTimeout)
|
||||
}, timeout: TestConstants.settleTimeout)
|
||||
|
||||
#expect(found)
|
||||
}
|
||||
@@ -535,11 +535,11 @@ struct ChatViewModelNoisePayloadTests {
|
||||
|
||||
let stored = await TestHelpers.waitUntil({
|
||||
viewModel.privateChats[peerID]?.contains(where: { $0.id == "pm-noise-1" && $0.content == "Secret hello" }) == true
|
||||
}, timeout: TestConstants.defaultTimeout)
|
||||
}, timeout: TestConstants.settleTimeout)
|
||||
|
||||
let acked = await TestHelpers.waitUntil({
|
||||
transport.sentDeliveryAcks.contains { $0.messageID == "pm-noise-1" && $0.peerID == peerID }
|
||||
}, timeout: TestConstants.defaultTimeout)
|
||||
}, timeout: TestConstants.settleTimeout)
|
||||
|
||||
#expect(stored)
|
||||
#expect(acked)
|
||||
@@ -579,7 +579,7 @@ struct ChatViewModelNoisePayloadTests {
|
||||
return name == "Bob"
|
||||
}
|
||||
return false
|
||||
}, timeout: TestConstants.defaultTimeout)
|
||||
}, timeout: TestConstants.settleTimeout)
|
||||
|
||||
#expect(delivered)
|
||||
}
|
||||
@@ -617,7 +617,7 @@ struct ChatViewModelNoisePayloadTests {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}, timeout: TestConstants.defaultTimeout)
|
||||
}, timeout: TestConstants.settleTimeout)
|
||||
|
||||
let conversationStoreUpdated = await TestHelpers.waitUntil({
|
||||
let messages = viewModel.conversations.conversationsByID[.directPeer(peerID)]?.messages ?? []
|
||||
@@ -626,7 +626,7 @@ struct ChatViewModelNoisePayloadTests {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}, timeout: TestConstants.defaultTimeout)
|
||||
}, timeout: TestConstants.settleTimeout)
|
||||
|
||||
#expect(privateChatUpdated)
|
||||
#expect(conversationStoreUpdated)
|
||||
@@ -730,7 +730,7 @@ struct ChatViewModelVerificationTests {
|
||||
|
||||
let bound = await TestHelpers.waitUntil({
|
||||
viewModel.unifiedPeerService.peers.contains { $0.peerID == peerID }
|
||||
}, timeout: TestConstants.defaultTimeout)
|
||||
}, timeout: TestConstants.settleTimeout)
|
||||
#expect(bound)
|
||||
|
||||
let qr = VerificationService.VerificationQR(
|
||||
@@ -982,7 +982,7 @@ struct ChatViewModelPeerTests {
|
||||
|
||||
let cleaned = await TestHelpers.waitUntil({
|
||||
!viewModel.unreadPrivateMessages.contains(stalePeer)
|
||||
}, timeout: TestConstants.defaultTimeout)
|
||||
}, timeout: TestConstants.settleTimeout)
|
||||
|
||||
#expect(cleaned)
|
||||
}
|
||||
|
||||
@@ -1179,6 +1179,71 @@ struct ConversationStoreTests {
|
||||
#expect(statusChangedIDs.isEmpty)
|
||||
}
|
||||
|
||||
@Test("peer-scoped receipt updates only authenticated direct aliases")
|
||||
@MainActor
|
||||
func peerScopedReceiptUpdatesOnlyAuthenticatedDirectAliases() {
|
||||
let store = ConversationStore()
|
||||
let ephemeralPeer = PeerID(str: "0102030405060708")
|
||||
let stablePeer = PeerID(hexData: Data(repeating: 0x08, count: 32))
|
||||
let otherPeer = PeerID(str: "1112131415161718")
|
||||
let ephemeral = ConversationID.directPeer(ephemeralPeer)
|
||||
let stable = ConversationID.directPeer(stablePeer)
|
||||
let other = ConversationID.directPeer(otherPeer)
|
||||
let messageID = "scoped-receipt"
|
||||
let mirrored = makeMessage(
|
||||
id: messageID,
|
||||
timestamp: 1,
|
||||
isPrivate: true,
|
||||
deliveryStatus: .sent
|
||||
)
|
||||
store.upsertByID(mirrored, in: ephemeral)
|
||||
store.upsertByID(mirrored, in: stable)
|
||||
store.upsertByID(
|
||||
makeMessage(
|
||||
id: messageID,
|
||||
timestamp: 1,
|
||||
isPrivate: true,
|
||||
deliveryStatus: .sent
|
||||
),
|
||||
in: other
|
||||
)
|
||||
store.upsertByID(
|
||||
makeMessage(id: messageID, timestamp: 1, deliveryStatus: .sent),
|
||||
in: .mesh
|
||||
)
|
||||
|
||||
var cancellables = Set<AnyCancellable>()
|
||||
var publishedIDs: [ConversationID] = []
|
||||
for id in [ephemeral, stable, other, .mesh] {
|
||||
store.conversation(for: id).objectWillChange
|
||||
.sink { publishedIDs.append(id) }
|
||||
.store(in: &cancellables)
|
||||
}
|
||||
var statusChangedIDs: [ConversationID] = []
|
||||
store.changes
|
||||
.sink { change in
|
||||
if case .statusChanged(let id, messageID, _) = change,
|
||||
messageID == "scoped-receipt" {
|
||||
statusChangedIDs.append(id)
|
||||
}
|
||||
}
|
||||
.store(in: &cancellables)
|
||||
|
||||
let delivered = DeliveryStatus.delivered(to: "bob", at: Date())
|
||||
#expect(store.setDeliveryStatus(
|
||||
delivered,
|
||||
forMessageID: messageID,
|
||||
inDirectPeerAliases: [ephemeralPeer, stablePeer]
|
||||
))
|
||||
|
||||
#expect(Set(publishedIDs) == Set([ephemeral, stable]))
|
||||
#expect(Set(statusChangedIDs) == Set([ephemeral, stable]))
|
||||
#expect(store.conversation(for: ephemeral).message(withID: messageID)?.deliveryStatus == delivered)
|
||||
#expect(store.conversation(for: stable).message(withID: messageID)?.deliveryStatus == delivered)
|
||||
#expect(store.conversation(for: other).message(withID: messageID)?.deliveryStatus == .sent)
|
||||
#expect(store.conversation(for: .mesh).message(withID: messageID)?.deliveryStatus == .sent)
|
||||
}
|
||||
|
||||
// MARK: - Invariant audit (field observability)
|
||||
|
||||
/// A store exercised through every intent family: public + geohash +
|
||||
|
||||
@@ -142,7 +142,7 @@ struct CourierEndToEndTests {
|
||||
))
|
||||
let deposited = await TestHelpers.waitUntil(
|
||||
{ aliceOut.first(ofType: .courierEnvelope) != nil },
|
||||
timeout: TestConstants.defaultTimeout
|
||||
timeout: TestConstants.settleTimeout
|
||||
)
|
||||
#expect(deposited)
|
||||
let depositPacket = try #require(aliceOut.first(ofType: .courierEnvelope))
|
||||
@@ -151,7 +151,7 @@ struct CourierEndToEndTests {
|
||||
carol._test_handlePacket(depositPacket, fromPeerID: alice.myPeerID, signingPublicKey: alice.noiseSigningPublicKeyData())
|
||||
let carried = await TestHelpers.waitUntil(
|
||||
{ !carol.courierStore.isEmpty },
|
||||
timeout: TestConstants.defaultTimeout
|
||||
timeout: TestConstants.settleTimeout
|
||||
)
|
||||
#expect(carried)
|
||||
|
||||
@@ -161,7 +161,7 @@ struct CourierEndToEndTests {
|
||||
bob.sendBroadcastAnnounce()
|
||||
let announced = await TestHelpers.waitUntil(
|
||||
{ bobOut.first(ofType: .announce) != nil },
|
||||
timeout: TestConstants.defaultTimeout
|
||||
timeout: TestConstants.settleTimeout
|
||||
)
|
||||
#expect(announced)
|
||||
let announcePacket = try #require(bobOut.first(ofType: .announce))
|
||||
@@ -169,7 +169,7 @@ struct CourierEndToEndTests {
|
||||
|
||||
let handedOver = await TestHelpers.waitUntil(
|
||||
{ carolOut.first(ofType: .courierEnvelope) != nil },
|
||||
timeout: TestConstants.defaultTimeout
|
||||
timeout: TestConstants.negativeWaitWindow
|
||||
)
|
||||
#expect(handedOver)
|
||||
// With CoreBluetooth disabled there is no physical link for the send
|
||||
@@ -183,7 +183,7 @@ struct CourierEndToEndTests {
|
||||
bob._test_handlePacket(handoverPacket, fromPeerID: carol.myPeerID)
|
||||
let received = await TestHelpers.waitUntil(
|
||||
{ !bobDelegate.snapshot().isEmpty },
|
||||
timeout: TestConstants.defaultTimeout
|
||||
timeout: TestConstants.settleTimeout
|
||||
)
|
||||
#expect(received)
|
||||
|
||||
@@ -229,7 +229,7 @@ struct CourierEndToEndTests {
|
||||
))
|
||||
let deposited = await TestHelpers.waitUntil(
|
||||
{ aliceOut.first(ofType: .courierEnvelope) != nil },
|
||||
timeout: TestConstants.defaultTimeout
|
||||
timeout: TestConstants.settleTimeout
|
||||
)
|
||||
#expect(deposited)
|
||||
let depositPacket = try #require(aliceOut.first(ofType: .courierEnvelope))
|
||||
@@ -237,7 +237,7 @@ struct CourierEndToEndTests {
|
||||
carol._test_handlePacket(depositPacket, fromPeerID: alice.myPeerID, signingPublicKey: alice.noiseSigningPublicKeyData())
|
||||
let carried = await TestHelpers.waitUntil(
|
||||
{ !carol.courierStore.isEmpty },
|
||||
timeout: TestConstants.defaultTimeout
|
||||
timeout: TestConstants.settleTimeout
|
||||
)
|
||||
#expect(carried)
|
||||
|
||||
@@ -245,7 +245,7 @@ struct CourierEndToEndTests {
|
||||
bob.sendBroadcastAnnounce()
|
||||
let announced = await TestHelpers.waitUntil(
|
||||
{ bobOut.first(ofType: .announce) != nil },
|
||||
timeout: TestConstants.defaultTimeout
|
||||
timeout: TestConstants.settleTimeout
|
||||
)
|
||||
#expect(announced)
|
||||
let announcePacket = try #require(bobOut.first(ofType: .announce))
|
||||
@@ -253,7 +253,7 @@ struct CourierEndToEndTests {
|
||||
|
||||
let handedOver = await TestHelpers.waitUntil(
|
||||
{ carolOut.first(ofType: .courierEnvelope) != nil },
|
||||
timeout: TestConstants.defaultTimeout
|
||||
timeout: TestConstants.settleTimeout
|
||||
)
|
||||
#expect(handedOver)
|
||||
let handoverPacket = try #require(carolOut.first(ofType: .courierEnvelope))
|
||||
@@ -265,7 +265,7 @@ struct CourierEndToEndTests {
|
||||
bob._test_handlePacket(handoverPacket, fromPeerID: carol.myPeerID)
|
||||
let delivered = await TestHelpers.waitUntil(
|
||||
{ !bobDelegate.snapshot().isEmpty },
|
||||
timeout: TestConstants.shortTimeout
|
||||
timeout: TestConstants.negativeWaitWindow
|
||||
)
|
||||
#expect(!delivered)
|
||||
}
|
||||
@@ -293,7 +293,7 @@ struct CourierEndToEndTests {
|
||||
))
|
||||
let deposited = await TestHelpers.waitUntil(
|
||||
{ aliceOut.first(ofType: .courierEnvelope) != nil },
|
||||
timeout: TestConstants.defaultTimeout
|
||||
timeout: TestConstants.settleTimeout
|
||||
)
|
||||
#expect(deposited)
|
||||
let depositPacket = try #require(aliceOut.first(ofType: .courierEnvelope))
|
||||
@@ -301,7 +301,7 @@ struct CourierEndToEndTests {
|
||||
carol._test_handlePacket(depositPacket, fromPeerID: alice.myPeerID, signingPublicKey: alice.noiseSigningPublicKeyData())
|
||||
let carried = await TestHelpers.waitUntil(
|
||||
{ !carol.courierStore.isEmpty },
|
||||
timeout: TestConstants.defaultTimeout
|
||||
timeout: TestConstants.settleTimeout
|
||||
)
|
||||
#expect(carried)
|
||||
|
||||
@@ -310,7 +310,7 @@ struct CourierEndToEndTests {
|
||||
|
||||
let leakedOnUnverifiedAnnounce = await TestHelpers.waitUntil(
|
||||
{ carolOut.count(ofType: .courierEnvelope) > 0 },
|
||||
timeout: TestConstants.shortTimeout
|
||||
timeout: TestConstants.negativeWaitWindow
|
||||
)
|
||||
#expect(!leakedOnUnverifiedAnnounce)
|
||||
#expect(!carol.courierStore.isEmpty)
|
||||
@@ -318,7 +318,7 @@ struct CourierEndToEndTests {
|
||||
bob.sendBroadcastAnnounce()
|
||||
let announced = await TestHelpers.waitUntil(
|
||||
{ bobOut.first(ofType: .announce) != nil },
|
||||
timeout: TestConstants.defaultTimeout
|
||||
timeout: TestConstants.negativeWaitWindow
|
||||
)
|
||||
#expect(announced)
|
||||
let verifiedAnnounce = try #require(bobOut.first(ofType: .announce))
|
||||
@@ -326,7 +326,7 @@ struct CourierEndToEndTests {
|
||||
|
||||
let handedOver = await TestHelpers.waitUntil(
|
||||
{ carolOut.count(ofType: .courierEnvelope) == 1 },
|
||||
timeout: TestConstants.defaultTimeout
|
||||
timeout: TestConstants.negativeWaitWindow
|
||||
)
|
||||
#expect(handedOver)
|
||||
#expect(!carol.courierStore.isEmpty)
|
||||
@@ -355,7 +355,7 @@ struct CourierEndToEndTests {
|
||||
))
|
||||
let deposited = await TestHelpers.waitUntil(
|
||||
{ aliceOut.first(ofType: .courierEnvelope) != nil },
|
||||
timeout: TestConstants.defaultTimeout
|
||||
timeout: TestConstants.settleTimeout
|
||||
)
|
||||
#expect(deposited)
|
||||
let depositPacket = try #require(aliceOut.first(ofType: .courierEnvelope))
|
||||
@@ -363,14 +363,14 @@ struct CourierEndToEndTests {
|
||||
carol._test_handlePacket(depositPacket, fromPeerID: alice.myPeerID, signingPublicKey: alice.noiseSigningPublicKeyData())
|
||||
let carried = await TestHelpers.waitUntil(
|
||||
{ !carol.courierStore.isEmpty },
|
||||
timeout: TestConstants.defaultTimeout
|
||||
timeout: TestConstants.settleTimeout
|
||||
)
|
||||
#expect(carried)
|
||||
|
||||
bob.sendBroadcastAnnounce()
|
||||
let announced = await TestHelpers.waitUntil(
|
||||
{ bobOut.first(ofType: .announce) != nil },
|
||||
timeout: TestConstants.defaultTimeout
|
||||
timeout: TestConstants.settleTimeout
|
||||
)
|
||||
#expect(announced)
|
||||
let directAnnounce = try #require(bobOut.first(ofType: .announce))
|
||||
@@ -385,7 +385,7 @@ struct CourierEndToEndTests {
|
||||
|
||||
let remoteHandover = await TestHelpers.waitUntil(
|
||||
{ carolOut.count(ofType: .courierEnvelope) == 1 },
|
||||
timeout: TestConstants.defaultTimeout
|
||||
timeout: TestConstants.negativeWaitWindow
|
||||
)
|
||||
#expect(remoteHandover)
|
||||
#expect(!carol.courierStore.isEmpty)
|
||||
@@ -398,7 +398,7 @@ struct CourierEndToEndTests {
|
||||
bob.sendBroadcastAnnounce()
|
||||
let reannounced = await TestHelpers.waitUntil(
|
||||
{ bobOut.all(ofType: .announce).contains { $0.timestamp != directAnnounce.timestamp } },
|
||||
timeout: TestConstants.defaultTimeout
|
||||
timeout: TestConstants.settleTimeout
|
||||
)
|
||||
#expect(reannounced)
|
||||
let freshAnnounce = try #require(
|
||||
@@ -410,7 +410,7 @@ struct CourierEndToEndTests {
|
||||
|
||||
let refloodedInCooldown = await TestHelpers.waitUntil(
|
||||
{ carolOut.count(ofType: .courierEnvelope) > 1 },
|
||||
timeout: TestConstants.shortTimeout
|
||||
timeout: TestConstants.negativeWaitWindow
|
||||
)
|
||||
#expect(!refloodedInCooldown)
|
||||
#expect(!carol.courierStore.isEmpty)
|
||||
@@ -424,7 +424,7 @@ struct CourierEndToEndTests {
|
||||
bob.sendBroadcastAnnounce()
|
||||
let announcedAgain = await TestHelpers.waitUntil(
|
||||
{ bobOut.all(ofType: .announce).contains { $0.timestamp != directAnnounce.timestamp && $0.timestamp != freshAnnounce.timestamp } },
|
||||
timeout: TestConstants.defaultTimeout
|
||||
timeout: TestConstants.settleTimeout
|
||||
)
|
||||
#expect(announcedAgain)
|
||||
let directAgain = try #require(
|
||||
@@ -434,7 +434,7 @@ struct CourierEndToEndTests {
|
||||
|
||||
let handedOverWithoutLinkProof = await TestHelpers.waitUntil(
|
||||
{ carolOut.count(ofType: .courierEnvelope) > 1 },
|
||||
timeout: TestConstants.shortTimeout
|
||||
timeout: TestConstants.negativeWaitWindow
|
||||
)
|
||||
#expect(!handedOverWithoutLinkProof)
|
||||
#expect(!carol.courierStore.isEmpty)
|
||||
@@ -457,7 +457,7 @@ struct CourierEndToEndTests {
|
||||
|
||||
let queuedPacket = await TestHelpers.waitUntil(
|
||||
{ aliceOut.first(ofType: .courierEnvelope) != nil },
|
||||
timeout: TestConstants.shortTimeout
|
||||
timeout: TestConstants.negativeWaitWindow
|
||||
)
|
||||
#expect(!queuedPacket)
|
||||
}
|
||||
@@ -494,7 +494,7 @@ struct CourierEndToEndTests {
|
||||
carol._test_handlePacket(packet, fromPeerID: alicePeerID, signingPublicKey: alice.getSigningPublicKeyData())
|
||||
let stored = await TestHelpers.waitUntil(
|
||||
{ !carol.courierStore.isEmpty },
|
||||
timeout: TestConstants.shortTimeout
|
||||
timeout: TestConstants.negativeWaitWindow
|
||||
)
|
||||
#expect(!stored)
|
||||
}
|
||||
@@ -532,7 +532,7 @@ struct CourierEndToEndTests {
|
||||
carol._test_handlePacket(packet, fromPeerID: alicePeerID, signingPublicKey: alice.getSigningPublicKeyData())
|
||||
let stored = await TestHelpers.waitUntil(
|
||||
{ !carol.courierStore.isEmpty },
|
||||
timeout: TestConstants.shortTimeout
|
||||
timeout: TestConstants.negativeWaitWindow
|
||||
)
|
||||
#expect(!stored)
|
||||
}
|
||||
@@ -575,7 +575,7 @@ struct CourierEndToEndTests {
|
||||
carol._test_handlePacket(packet, fromPeerID: mallory.myPeerID, preseedPeer: false)
|
||||
let stored = await TestHelpers.waitUntil(
|
||||
{ !carol.courierStore.isEmpty },
|
||||
timeout: TestConstants.shortTimeout
|
||||
timeout: TestConstants.negativeWaitWindow
|
||||
)
|
||||
#expect(!stored)
|
||||
}
|
||||
@@ -602,14 +602,14 @@ struct CourierEndToEndTests {
|
||||
|
||||
let delivered = await TestHelpers.waitUntil(
|
||||
{ !bobDelegate.snapshot().isEmpty },
|
||||
timeout: TestConstants.defaultTimeout
|
||||
timeout: TestConstants.settleTimeout
|
||||
)
|
||||
#expect(delivered)
|
||||
// Give a duplicate delivery a chance to surface, then confirm the
|
||||
// second copy never reached the delegate.
|
||||
let duplicated = await TestHelpers.waitUntil(
|
||||
{ bobDelegate.snapshot().count > 1 },
|
||||
timeout: TestConstants.shortTimeout
|
||||
timeout: TestConstants.negativeWaitWindow
|
||||
)
|
||||
#expect(!duplicated)
|
||||
#expect(bobDelegate.snapshot().count == 1)
|
||||
@@ -629,7 +629,7 @@ struct CourierEndToEndTests {
|
||||
|
||||
let initiated = await TestHelpers.waitUntil(
|
||||
{ outbound.count(ofType: .noiseHandshake) > 0 },
|
||||
timeout: TestConstants.shortTimeout
|
||||
timeout: TestConstants.negativeWaitWindow
|
||||
)
|
||||
#expect(!initiated)
|
||||
|
||||
@@ -639,7 +639,7 @@ struct CourierEndToEndTests {
|
||||
ble.sendDeliveryAck(for: "msg-2", to: present)
|
||||
let initiatedForPresent = await TestHelpers.waitUntil(
|
||||
{ outbound.count(ofType: .noiseHandshake) > 0 },
|
||||
timeout: TestConstants.defaultTimeout
|
||||
timeout: TestConstants.settleTimeout
|
||||
)
|
||||
#expect(initiatedForPresent)
|
||||
}
|
||||
|
||||
@@ -87,7 +87,7 @@ struct PrekeyEndToEndTests {
|
||||
peer.sendBroadcastAnnounce()
|
||||
let published = await TestHelpers.waitUntil(
|
||||
{ tap.first(ofType: .announce) != nil && tap.first(ofType: .prekeyBundle) != nil },
|
||||
timeout: TestConstants.defaultTimeout
|
||||
timeout: TestConstants.settleTimeout
|
||||
)
|
||||
#expect(published)
|
||||
return (
|
||||
@@ -124,7 +124,7 @@ struct PrekeyEndToEndTests {
|
||||
|
||||
let cached = await TestHelpers.waitUntil(
|
||||
{ alice.prekeyBundleStore.hasUsableBundle(for: bob.noiseStaticPublicKeyData()) },
|
||||
timeout: TestConstants.defaultTimeout
|
||||
timeout: TestConstants.settleTimeout
|
||||
)
|
||||
#expect(cached)
|
||||
|
||||
@@ -138,7 +138,7 @@ struct PrekeyEndToEndTests {
|
||||
))
|
||||
let deposited = await TestHelpers.waitUntil(
|
||||
{ aliceOut.first(ofType: .courierEnvelope) != nil },
|
||||
timeout: TestConstants.defaultTimeout
|
||||
timeout: TestConstants.settleTimeout
|
||||
)
|
||||
#expect(deposited)
|
||||
let depositPacket = try #require(aliceOut.first(ofType: .courierEnvelope))
|
||||
@@ -149,7 +149,7 @@ struct PrekeyEndToEndTests {
|
||||
carol._test_handlePacket(depositPacket, fromPeerID: alice.myPeerID, signingPublicKey: alice.noiseSigningPublicKeyData())
|
||||
let carried = await TestHelpers.waitUntil(
|
||||
{ !carol.courierStore.isEmpty },
|
||||
timeout: TestConstants.defaultTimeout
|
||||
timeout: TestConstants.settleTimeout
|
||||
)
|
||||
#expect(carried)
|
||||
|
||||
@@ -158,7 +158,7 @@ struct PrekeyEndToEndTests {
|
||||
bob.sendBroadcastAnnounce()
|
||||
let reannounced = await TestHelpers.waitUntil(
|
||||
{ bobOut.first(ofType: .announce) != nil },
|
||||
timeout: TestConstants.defaultTimeout
|
||||
timeout: TestConstants.settleTimeout
|
||||
)
|
||||
#expect(reannounced)
|
||||
let handoverTrigger = try #require(bobOut.first(ofType: .announce))
|
||||
@@ -166,7 +166,7 @@ struct PrekeyEndToEndTests {
|
||||
|
||||
let handedOver = await TestHelpers.waitUntil(
|
||||
{ carolOut.first(ofType: .courierEnvelope) != nil },
|
||||
timeout: TestConstants.defaultTimeout
|
||||
timeout: TestConstants.settleTimeout
|
||||
)
|
||||
#expect(handedOver)
|
||||
let handoverPacket = try #require(carolOut.first(ofType: .courierEnvelope))
|
||||
@@ -178,7 +178,7 @@ struct PrekeyEndToEndTests {
|
||||
bob._test_handlePacket(handoverPacket, fromPeerID: carol.myPeerID)
|
||||
let received = await TestHelpers.waitUntil(
|
||||
{ !bobDelegate.snapshot().isEmpty },
|
||||
timeout: TestConstants.defaultTimeout
|
||||
timeout: TestConstants.settleTimeout
|
||||
)
|
||||
#expect(received)
|
||||
|
||||
@@ -207,7 +207,7 @@ struct PrekeyEndToEndTests {
|
||||
bob._test_handlePacket(redelivery, fromPeerID: carol.myPeerID)
|
||||
let redelivered = await TestHelpers.waitUntil(
|
||||
{ bobDelegate.snapshot().count == 2 },
|
||||
timeout: TestConstants.shortTimeout
|
||||
timeout: TestConstants.negativeWaitWindow
|
||||
)
|
||||
#expect(!redelivered)
|
||||
#expect(bobDelegate.snapshot().count == 1)
|
||||
@@ -235,7 +235,7 @@ struct PrekeyEndToEndTests {
|
||||
))
|
||||
let deposited = await TestHelpers.waitUntil(
|
||||
{ aliceOut.first(ofType: .courierEnvelope) != nil },
|
||||
timeout: TestConstants.defaultTimeout
|
||||
timeout: TestConstants.settleTimeout
|
||||
)
|
||||
#expect(deposited)
|
||||
let depositPacket = try #require(aliceOut.first(ofType: .courierEnvelope))
|
||||
@@ -248,7 +248,7 @@ struct PrekeyEndToEndTests {
|
||||
bob._test_handlePacket(depositPacket, fromPeerID: alice.myPeerID, preseedPeer: false)
|
||||
let received = await TestHelpers.waitUntil(
|
||||
{ !bobDelegate.snapshot().isEmpty },
|
||||
timeout: TestConstants.defaultTimeout
|
||||
timeout: TestConstants.settleTimeout
|
||||
)
|
||||
#expect(received)
|
||||
let delivered = try #require(bobDelegate.snapshot().first)
|
||||
@@ -272,7 +272,7 @@ struct PrekeyEndToEndTests {
|
||||
|
||||
let cached = await TestHelpers.waitUntil(
|
||||
{ alice.prekeyBundleStore.hasUsableBundle(for: bob.noiseStaticPublicKeyData()) },
|
||||
timeout: TestConstants.shortTimeout
|
||||
timeout: TestConstants.negativeWaitWindow
|
||||
)
|
||||
#expect(!cached)
|
||||
}
|
||||
@@ -310,7 +310,7 @@ struct PrekeyEndToEndTests {
|
||||
|
||||
let cached = await TestHelpers.waitUntil(
|
||||
{ alice.prekeyBundleStore.hasUsableBundle(for: bob.noiseStaticPublicKeyData()) },
|
||||
timeout: TestConstants.shortTimeout
|
||||
timeout: TestConstants.negativeWaitWindow
|
||||
)
|
||||
#expect(!cached)
|
||||
}
|
||||
@@ -328,7 +328,7 @@ struct PrekeyEndToEndTests {
|
||||
|
||||
let cached = await TestHelpers.waitUntil(
|
||||
{ alice.prekeyBundleStore.hasUsableBundle(for: bob.noiseStaticPublicKeyData()) },
|
||||
timeout: TestConstants.defaultTimeout
|
||||
timeout: TestConstants.settleTimeout
|
||||
)
|
||||
#expect(cached)
|
||||
// The verified bundle now participates in Alice's sync rounds.
|
||||
@@ -364,7 +364,7 @@ struct PrekeyEndToEndTests {
|
||||
|
||||
let cached = await TestHelpers.waitUntil(
|
||||
{ alice.prekeyBundleStore.hasUsableBundle(for: bob.noiseStaticPublicKeyData()) },
|
||||
timeout: TestConstants.shortTimeout
|
||||
timeout: TestConstants.negativeWaitWindow
|
||||
)
|
||||
#expect(!cached)
|
||||
#expect(!alice._test_hasGossipPrekeyBundle(for: bob.myPeerID))
|
||||
@@ -396,7 +396,7 @@ struct PrekeyEndToEndTests {
|
||||
|
||||
let cached = await TestHelpers.waitUntil(
|
||||
{ alice.prekeyBundleStore.hasUsableBundle(for: bob.noiseStaticPublicKeyData()) },
|
||||
timeout: TestConstants.shortTimeout
|
||||
timeout: TestConstants.negativeWaitWindow
|
||||
)
|
||||
#expect(!cached)
|
||||
#expect(!alice._test_hasGossipPrekeyBundle(for: bob.myPeerID))
|
||||
|
||||
@@ -37,7 +37,7 @@ struct GossipSyncManagerTests {
|
||||
}
|
||||
|
||||
manager.scheduleInitialSyncToPeer(PeerID(str: "FFFFFFFFFFFFFFFF"), delaySeconds: 0.0)
|
||||
try await TestHelpers.waitFor({ delegate.lastPacket != nil }, timeout: TestConstants.shortTimeout)
|
||||
try await TestHelpers.waitFor({ delegate.lastPacket != nil }, timeout: TestConstants.settleTimeout)
|
||||
}
|
||||
|
||||
let lastPacket = try #require(delegate.lastPacket, "Expected sync packet to be sent")
|
||||
@@ -394,7 +394,7 @@ struct GossipSyncManagerTests {
|
||||
)
|
||||
manager.handleRequestSync(from: peer, request: request)
|
||||
|
||||
try await TestHelpers.waitFor({ delegate.packets.count == 2 }, timeout: TestConstants.shortTimeout)
|
||||
try await TestHelpers.waitFor({ delegate.packets.count == 2 }, timeout: TestConstants.settleTimeout)
|
||||
// Barrier: flush the sync queue so a late third packet would be visible.
|
||||
manager._performMaintenanceSynchronously(now: Date())
|
||||
let sentPackets = delegate.packets
|
||||
@@ -477,7 +477,7 @@ struct GossipSyncManagerTests {
|
||||
manager.handleRequestSync(from: peer, request: request)
|
||||
manager.handleRequestSync(from: peer, request: request)
|
||||
|
||||
try await TestHelpers.waitFor({ delegate.packets.count >= 1 }, timeout: TestConstants.shortTimeout)
|
||||
try await TestHelpers.waitFor({ delegate.packets.count >= 1 }, timeout: TestConstants.settleTimeout)
|
||||
// Barrier: both requests have been processed once this returns.
|
||||
manager._performMaintenanceSynchronously(now: Date())
|
||||
#expect(delegate.packets.count == 1)
|
||||
@@ -498,7 +498,7 @@ struct GossipSyncManagerTests {
|
||||
|
||||
manager.scheduleInitialSyncToPeer(PeerID(str: "FFFFFFFFFFFFFFFF"), delaySeconds: 0.0)
|
||||
|
||||
try await TestHelpers.waitFor({ delegate.packets.count == 1 }, timeout: TestConstants.shortTimeout)
|
||||
try await TestHelpers.waitFor({ delegate.packets.count == 1 }, timeout: TestConstants.settleTimeout)
|
||||
let packet = try #require(delegate.packets.first)
|
||||
let request = try #require(RequestSyncPacket.decode(from: packet.payload))
|
||||
let types = try #require(request.types)
|
||||
@@ -553,7 +553,7 @@ struct GossipSyncManagerTests {
|
||||
let request = RequestSyncPacket(p: 4, m: 1, data: Data(), types: .fragment)
|
||||
manager.handleRequestSync(from: peer, request: request)
|
||||
|
||||
try await TestHelpers.waitFor({ delegate.packets.count == 1 }, timeout: TestConstants.shortTimeout)
|
||||
try await TestHelpers.waitFor({ delegate.packets.count == 1 }, timeout: TestConstants.settleTimeout)
|
||||
let sentPackets = delegate.packets
|
||||
#expect(sentPackets.count == 1)
|
||||
#expect(sentPackets[0].type == MessageType.fragment.rawValue)
|
||||
@@ -615,7 +615,7 @@ struct GossipSyncManagerTests {
|
||||
)
|
||||
manager.handleRequestSync(from: PeerID(str: "FFFFFFFFFFFFFFFF"), request: request)
|
||||
|
||||
try await TestHelpers.waitFor({ delegate.packets.count == 1 }, timeout: TestConstants.shortTimeout)
|
||||
try await TestHelpers.waitFor({ delegate.packets.count == 1 }, timeout: TestConstants.settleTimeout)
|
||||
// Barrier: flush the sync queue so a late second packet would be visible.
|
||||
manager._performMaintenanceSynchronously(now: Date())
|
||||
let sentPackets = delegate.packets
|
||||
@@ -641,7 +641,7 @@ struct GossipSyncManagerTests {
|
||||
let stalledID = try #require(Data(hexString: "0102030405060708"))
|
||||
manager.requestMissingFragments(fragmentIDs: [stalledID])
|
||||
|
||||
try await TestHelpers.waitFor({ delegate.packets.count == 1 }, timeout: TestConstants.shortTimeout)
|
||||
try await TestHelpers.waitFor({ delegate.packets.count == 1 }, timeout: TestConstants.settleTimeout)
|
||||
let sent = try #require(delegate.packets.first)
|
||||
#expect(sent.type == MessageType.requestSync.rawValue)
|
||||
#expect(sent.ttl == 0)
|
||||
@@ -697,7 +697,7 @@ struct GossipSyncManagerTests {
|
||||
// And a .prekeyBundle sync request is answered with the stored packet.
|
||||
let request = RequestSyncPacket(p: 7, m: 1, data: Data(), types: .prekeyBundle)
|
||||
manager.handleRequestSync(from: PeerID(str: "FFFFFFFFFFFFFFFF"), request: request)
|
||||
try await TestHelpers.waitFor({ delegate.packets.count == 1 }, timeout: TestConstants.shortTimeout)
|
||||
try await TestHelpers.waitFor({ delegate.packets.count == 1 }, timeout: TestConstants.settleTimeout)
|
||||
let served = try #require(delegate.packets.first)
|
||||
#expect(served.type == MessageType.prekeyBundle.rawValue)
|
||||
#expect(served.isRSR)
|
||||
@@ -774,7 +774,7 @@ struct GossipSyncManagerTests {
|
||||
)
|
||||
let restored = await TestHelpers.waitUntil(
|
||||
{ second._messageCount(for: PeerID(hexData: senderID)) == 1 },
|
||||
timeout: TestConstants.shortTimeout
|
||||
timeout: TestConstants.settleTimeout
|
||||
)
|
||||
#expect(restored)
|
||||
}
|
||||
@@ -810,6 +810,45 @@ struct GossipSyncManagerTests {
|
||||
#expect(manager._messageCount(for: PeerID(hexData: senderID)) == 0)
|
||||
}
|
||||
|
||||
/// Clearing the mesh timeline must leave nothing behind on disk: a
|
||||
/// relaunch that restored the archive would undo the clear.
|
||||
@Test func removeAllPublicMessagesErasesTheArchiveOnDisk() async throws {
|
||||
let fileURL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("gossip-archive-\(UUID().uuidString).json")
|
||||
defer { try? FileManager.default.removeItem(at: fileURL) }
|
||||
|
||||
let senderID = try #require(Data(hexString: "1122334455667788"))
|
||||
let packet = BitchatPacket(
|
||||
type: MessageType.message.rawValue,
|
||||
senderID: senderID,
|
||||
recipientID: nil,
|
||||
timestamp: UInt64(Date().timeIntervalSince1970 * 1000),
|
||||
payload: Data([0x01, 0x02]),
|
||||
signature: nil,
|
||||
ttl: 1
|
||||
)
|
||||
|
||||
let manager = GossipSyncManager(
|
||||
myPeerID: myPeerID,
|
||||
requestSyncManager: RequestSyncManager(),
|
||||
archive: GossipMessageArchive(fileURL: fileURL)
|
||||
)
|
||||
manager.onPublicPacketSeen(packet)
|
||||
manager._performMaintenanceSynchronously(now: Date())
|
||||
#expect(FileManager.default.fileExists(atPath: fileURL.path))
|
||||
|
||||
manager.removeAllPublicMessages()
|
||||
|
||||
let erased = await TestHelpers.waitUntil(
|
||||
{
|
||||
!FileManager.default.fileExists(atPath: fileURL.path)
|
||||
&& manager._messageCount(for: PeerID(hexData: senderID)) == 0
|
||||
},
|
||||
timeout: TestConstants.settleTimeout
|
||||
)
|
||||
#expect(erased)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private final class RecordingDelegate: GossipSyncManager.Delegate {
|
||||
|
||||
@@ -65,11 +65,15 @@ final class MockTransport: Transport, PrivateMediaDeletionPersisting {
|
||||
var peerFingerprints: [PeerID: String] = [:]
|
||||
var peerNoiseStates: [PeerID: LazyHandshakeState] = [:]
|
||||
var privateMediaPolicies: [PeerID: PrivateMediaSendPolicy] = [:]
|
||||
var privateMediaReceiptSessionGenerations: [PeerID: UUID] = [:]
|
||||
var persistDeletedPrivateMediaResult = true
|
||||
var deferDeletedPrivateMediaPersistence = false
|
||||
private var pendingDeletedPrivateMediaCompletions: [
|
||||
@MainActor (Bool) -> Void
|
||||
] = []
|
||||
/// Optional synchronous hook for send-ordering tests (for example, an ack
|
||||
/// arriving before the router's send call returns).
|
||||
var onSendPrivateMessage: (@MainActor (_ messageID: String) -> Void)?
|
||||
private let mockKeychain = MockKeychain()
|
||||
|
||||
// MARK: - Transport Protocol Implementation
|
||||
@@ -174,6 +178,11 @@ final class MockTransport: Transport, PrivateMediaDeletionPersisting {
|
||||
|
||||
func sendPrivateMessage(_ content: String, to peerID: PeerID, recipientNickname: String, messageID: String) {
|
||||
sentPrivateMessages.append((content, peerID, recipientNickname, messageID))
|
||||
if let onSendPrivateMessage {
|
||||
MainActor.assumeIsolated {
|
||||
onSendPrivateMessage(messageID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func sendReadReceipt(_ receipt: ReadReceipt, to peerID: PeerID) {
|
||||
@@ -215,6 +224,12 @@ final class MockTransport: Transport, PrivateMediaDeletionPersisting {
|
||||
privateMediaPolicies[peerID] ?? .encrypted
|
||||
}
|
||||
|
||||
func authenticatedPrivateMediaReceiptSessionGeneration(
|
||||
to peerID: PeerID
|
||||
) -> UUID? {
|
||||
privateMediaReceiptSessionGenerations[peerID]
|
||||
}
|
||||
|
||||
func resolvePrivateMediaSendPolicy(
|
||||
to peerID: PeerID,
|
||||
completion: @escaping @MainActor (PrivateMediaSendPolicy) -> Void
|
||||
|
||||
@@ -392,7 +392,7 @@ final class NearbyNotesCounterTests: XCTestCase {
|
||||
}
|
||||
|
||||
private func waitUntil(
|
||||
timeout: TimeInterval = 1.0,
|
||||
timeout: TimeInterval = TestConstants.settleTimeout,
|
||||
condition: @escaping @MainActor () -> Bool
|
||||
) async -> Bool {
|
||||
let deadline = Date().addingTimeInterval(timeout)
|
||||
|
||||
@@ -723,9 +723,9 @@ struct NoiseCoverageTests {
|
||||
// A failed startup requirement must not strand a late thread in
|
||||
// the blocking test double after the test has returned.
|
||||
oldSession.resumeDecrypt()
|
||||
_ = decryptResult.wait(timeout: 5)
|
||||
_ = decryptResult.wait(timeout: TestConstants.settleTimeout)
|
||||
if let promotionResultForCleanup {
|
||||
_ = promotionResultForCleanup.wait(timeout: 5)
|
||||
_ = promotionResultForCleanup.wait(timeout: TestConstants.settleTimeout)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -751,15 +751,19 @@ struct NoiseCoverageTests {
|
||||
promotionThread.name = "NoiseCoverageTests.staleDecrypt.promote"
|
||||
promotionThread.qualityOfService = .userInitiated
|
||||
promotionThread.start()
|
||||
try #require(promotionStarted.wait(timeout: .now() + 5) == .success)
|
||||
try #require(promotionStarted.wait(timeout: .now() + TestConstants.settleTimeout) == .success)
|
||||
#expect(
|
||||
// test-timing-ok: a NEGATIVE wait — it asserts the promotion has
|
||||
// NOT completed yet, so a long deadline would only make the suite
|
||||
// slow while still passing. A starved runner can only make this
|
||||
// more likely to hold, never less.
|
||||
promotionResult.wait(timeout: 0.05) == nil,
|
||||
"Promotion must wait for the exact decrypting-session lease"
|
||||
)
|
||||
|
||||
oldSession.resumeDecrypt()
|
||||
let decrypted = try #require(decryptResult.wait(timeout: 5)).get()
|
||||
_ = try #require(promotionResult.wait(timeout: 5)).get()
|
||||
let decrypted = try #require(decryptResult.wait(timeout: TestConstants.settleTimeout)).get()
|
||||
_ = try #require(promotionResult.wait(timeout: TestConstants.settleTimeout)).get()
|
||||
|
||||
#expect(decrypted.plaintext == Data("old session".utf8))
|
||||
#expect(decrypted.sessionGeneration == oldGeneration)
|
||||
|
||||
@@ -580,8 +580,16 @@ final class GeoRelayDirectoryTests: XCTestCase {
|
||||
/// constrained CI runners (2-core, serialized testing) can starve the
|
||||
/// detached utility-priority fetch task for seconds before it runs, and
|
||||
/// a successful wait returns as soon as the condition becomes true.
|
||||
/// Default deliberately far larger than the work being awaited.
|
||||
///
|
||||
/// The directory performs its fetch in a `Task.detached(priority: .utility)`,
|
||||
/// and utility priority competes with every other suite on a CI runner. At
|
||||
/// ten seconds the retry-scheduling test timed out at exactly 10.06s with
|
||||
/// the retry never scheduled — which reads like a missing retry rather than
|
||||
/// a starved background task. Returning as soon as the condition holds means
|
||||
/// a longer deadline only extends the genuine-failure case.
|
||||
private func waitUntil(
|
||||
timeout: TimeInterval = 10.0,
|
||||
timeout: TimeInterval = TestConstants.settleTimeout,
|
||||
condition: @escaping @MainActor () async -> Bool
|
||||
) async -> Bool {
|
||||
let deadline = Date().addingTimeInterval(timeout)
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -188,7 +188,7 @@ struct PTTBurstPlayerTests {
|
||||
_ condition: () -> Bool,
|
||||
sourceLocation: SourceLocation = #_sourceLocation
|
||||
) async {
|
||||
let deadline = ContinuousClock.now.advanced(by: .seconds(5))
|
||||
let deadline = ContinuousClock.now.advanced(by: .seconds(TestConstants.settleTimeout))
|
||||
while !condition(), ContinuousClock.now < deadline {
|
||||
await Task.yield()
|
||||
try? await Task.sleep(nanoseconds: 1_000_000)
|
||||
|
||||
@@ -749,12 +749,30 @@ private final class PerfDeliveryContext: ChatDeliveryContext {
|
||||
|
||||
func notifyUIChanged() {}
|
||||
func markMessageDelivered(_ messageID: String) {}
|
||||
func markMessageDelivered(_ messageID: String, from peerIDs: Set<PeerID>) {}
|
||||
func confirmPrivateMediaDelivery(_ messageID: String) {}
|
||||
func isOutgoingPrivateMessage(_ messageID: String, toAny peerIDs: Set<PeerID>) -> Bool {
|
||||
true
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
func setDeliveryStatus(_ status: DeliveryStatus, forMessageID messageID: String) -> Bool {
|
||||
store.setDeliveryStatus(status, forMessageID: messageID)
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
func setDeliveryStatus(
|
||||
_ status: DeliveryStatus,
|
||||
forMessageID messageID: String,
|
||||
inDirectPeerAliases peerIDs: Set<PeerID>
|
||||
) -> Bool {
|
||||
store.setDeliveryStatus(
|
||||
status,
|
||||
forMessageID: messageID,
|
||||
inDirectPeerAliases: peerIDs
|
||||
)
|
||||
}
|
||||
|
||||
func deliveryStatus(forMessageID messageID: String) -> DeliveryStatus? {
|
||||
store.deliveryStatus(forMessageID: messageID)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
import BitFoundation
|
||||
import Foundation
|
||||
import Testing
|
||||
@testable import bitchat
|
||||
|
||||
struct BLEMeshPingTrackerTests {
|
||||
private func makeProbe(peerID: PeerID) -> BLEMeshPingProbe {
|
||||
BLEMeshPingProbe(
|
||||
peerID: peerID,
|
||||
sentAt: Date(timeIntervalSince1970: 1_000),
|
||||
lifecycleGeneration: 1,
|
||||
completion: { _ in },
|
||||
timeout: DispatchWorkItem {}
|
||||
)
|
||||
}
|
||||
|
||||
@Test func resolveReturnsProbeOnlyForTheProbedPeer() {
|
||||
var tracker = BLEMeshPingTracker()
|
||||
let nonce = Data([1, 2, 3, 4, 5, 6, 7, 8])
|
||||
let probed = PeerID(str: "aaaaaaaaaaaaaaaa")
|
||||
tracker.register(makeProbe(peerID: probed), nonce: nonce)
|
||||
|
||||
// A pong claiming the right nonce from the wrong peer must not
|
||||
// consume the probe.
|
||||
let wrongPeer = tracker.resolve(nonce: nonce, from: PeerID(str: "bbbbbbbbbbbbbbbb"))
|
||||
#expect(wrongPeer == nil)
|
||||
let rightPeer = tracker.resolve(nonce: nonce, from: probed)
|
||||
#expect(rightPeer != nil)
|
||||
// Consumed exactly once.
|
||||
let secondResolve = tracker.resolve(nonce: nonce, from: probed)
|
||||
#expect(secondResolve == nil)
|
||||
}
|
||||
|
||||
@Test func expireConsumesTheProbeSoResolveCannotFireTwice() {
|
||||
var tracker = BLEMeshPingTracker()
|
||||
let nonce = Data([9, 9, 9, 9, 9, 9, 9, 9])
|
||||
let probed = PeerID(str: "aaaaaaaaaaaaaaaa")
|
||||
tracker.register(makeProbe(peerID: probed), nonce: nonce)
|
||||
|
||||
let firstExpire = tracker.expire(nonce: nonce)
|
||||
#expect(firstExpire != nil)
|
||||
let secondExpire = tracker.expire(nonce: nonce)
|
||||
#expect(secondExpire == nil)
|
||||
let resolveAfterExpire = tracker.resolve(nonce: nonce, from: probed)
|
||||
#expect(resolveAfterExpire == nil)
|
||||
}
|
||||
|
||||
@Test func inboundBudgetIsPerLinkAndBounded() {
|
||||
var tracker = BLEMeshPingTracker()
|
||||
let now = Date(timeIntervalSince1970: 2_000)
|
||||
let linkA = PeerID(str: "aaaaaaaaaaaaaaaa")
|
||||
let linkB = PeerID(str: "bbbbbbbbbbbbbbbb")
|
||||
|
||||
var allowedOnA = 0
|
||||
for _ in 0..<(TransportConfig.meshPingInboundMaxPerLink + 5) {
|
||||
if tracker.shouldRespond(toLink: linkA, now: now) { allowedOnA += 1 }
|
||||
}
|
||||
#expect(allowedOnA == TransportConfig.meshPingInboundMaxPerLink)
|
||||
// One saturated link must not consume another link's budget.
|
||||
let allowedOnB = tracker.shouldRespond(toLink: linkB, now: now)
|
||||
#expect(allowedOnB)
|
||||
}
|
||||
|
||||
@Test func resetDropsProbesRestoresBudgetAndHandsBackTimeouts() {
|
||||
var tracker = BLEMeshPingTracker()
|
||||
let now = Date(timeIntervalSince1970: 3_000)
|
||||
let link = PeerID(str: "aaaaaaaaaaaaaaaa")
|
||||
let nonce = Data([4, 4, 4, 4, 4, 4, 4, 4])
|
||||
tracker.register(makeProbe(peerID: link), nonce: nonce)
|
||||
for _ in 0..<TransportConfig.meshPingInboundMaxPerLink {
|
||||
_ = tracker.shouldRespond(toLink: link, now: now)
|
||||
}
|
||||
let saturated = tracker.shouldRespond(toLink: link, now: now)
|
||||
#expect(!saturated)
|
||||
|
||||
let timeouts = tracker.reset()
|
||||
|
||||
#expect(timeouts.count == 1)
|
||||
let resolveAfterReset = tracker.resolve(nonce: nonce, from: link)
|
||||
#expect(resolveAfterReset == nil)
|
||||
let allowedAfterReset = tracker.shouldRespond(toLink: link, now: now)
|
||||
#expect(allowedAfterReset)
|
||||
}
|
||||
}
|
||||
@@ -203,6 +203,134 @@ struct BridgeCourierServiceTests {
|
||||
#expect(confirmed.sealRequests.isEmpty)
|
||||
}
|
||||
|
||||
@Test func sameMessageIDIsScopedByRecipientAcrossRejectedActiveAndPersistedState() {
|
||||
let fileURL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("bridge-dedup-\(UUID().uuidString).json")
|
||||
defer { try? FileManager.default.removeItem(at: fileURL) }
|
||||
let rejectedKey = Fixture.randomKey()
|
||||
let firstKey = Fixture.randomKey()
|
||||
let secondKey = Fixture.randomKey()
|
||||
let thirdKey = Fixture.randomKey()
|
||||
let messageID = "recipient-scoped-collision"
|
||||
|
||||
let fixture = Fixture(dedupStore: BridgeDropDedupStore(fileURL: fileURL))
|
||||
fixture.sealResult = makeEnvelope(
|
||||
recipientKey: rejectedKey,
|
||||
ciphertext: Data(
|
||||
repeating: 7,
|
||||
count: BridgeCourierService.Limits.maxDropEnvelopeBytes + 1
|
||||
)
|
||||
)
|
||||
var rejectedResults: [Bool] = []
|
||||
fixture.service.depositDrop(
|
||||
content: "rejected",
|
||||
messageID: messageID,
|
||||
recipientNoiseKey: rejectedKey
|
||||
) { rejectedResults.append($0) }
|
||||
#expect(rejectedResults == [false])
|
||||
|
||||
fixture.sealResult = makeEnvelope(recipientKey: firstKey)
|
||||
fixture.automaticPublishResult = nil
|
||||
var firstResults: [Bool] = []
|
||||
var secondResults: [Bool] = []
|
||||
var duplicateFirstResults: [Bool] = []
|
||||
fixture.service.depositDrop(
|
||||
content: "first",
|
||||
messageID: messageID,
|
||||
recipientNoiseKey: firstKey
|
||||
) { firstResults.append($0) }
|
||||
fixture.service.depositDrop(
|
||||
content: "second",
|
||||
messageID: messageID,
|
||||
recipientNoiseKey: secondKey
|
||||
) { secondResults.append($0) }
|
||||
fixture.service.depositDrop(
|
||||
content: "first duplicate",
|
||||
messageID: messageID,
|
||||
recipientNoiseKey: firstKey
|
||||
) { duplicateFirstResults.append($0) }
|
||||
|
||||
#expect(fixture.publishedEvents.count == 2)
|
||||
#expect(fixture.pendingPublishCompletions.count == 2)
|
||||
#expect(duplicateFirstResults == [false])
|
||||
#expect(firstResults.isEmpty)
|
||||
#expect(secondResults.isEmpty)
|
||||
|
||||
fixture.resolveNextPublish(true)
|
||||
fixture.resolveNextPublish(true)
|
||||
#expect(firstResults == [true])
|
||||
#expect(secondResults == [true])
|
||||
fixture.service.flushDedupSnapshot()
|
||||
|
||||
let relaunched = Fixture(
|
||||
dedupStore: BridgeDropDedupStore(fileURL: fileURL)
|
||||
)
|
||||
relaunched.sealResult = makeEnvelope(recipientKey: thirdKey)
|
||||
var relaunchResults: [Bool] = []
|
||||
relaunched.service.depositDrop(
|
||||
content: "first",
|
||||
messageID: messageID,
|
||||
recipientNoiseKey: firstKey
|
||||
) { relaunchResults.append($0) }
|
||||
relaunched.service.depositDrop(
|
||||
content: "second",
|
||||
messageID: messageID,
|
||||
recipientNoiseKey: secondKey
|
||||
) { relaunchResults.append($0) }
|
||||
relaunched.service.depositDrop(
|
||||
content: "third",
|
||||
messageID: messageID,
|
||||
recipientNoiseKey: thirdKey
|
||||
) { relaunchResults.append($0) }
|
||||
|
||||
#expect(relaunchResults == [false, false, true])
|
||||
#expect(relaunched.sealRequests.count == 1)
|
||||
#expect(relaunched.sealRequests.first?.key == thirdKey)
|
||||
#expect(relaunched.publishedEvents.count == 1)
|
||||
}
|
||||
|
||||
@Test func legacyPublishedMessageIDIsWildcardUntilItsOriginalExpiry() {
|
||||
let fileURL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("bridge-dedup-\(UUID().uuidString).json")
|
||||
defer { try? FileManager.default.removeItem(at: fileURL) }
|
||||
var date = Date()
|
||||
let messageID = "legacy-wildcard"
|
||||
let recipientKey = Fixture.randomKey()
|
||||
let store = BridgeDropDedupStore(fileURL: fileURL)
|
||||
store.save(BridgeDropDedupStore.Snapshot(
|
||||
publishedDropKeys: [messageID: date],
|
||||
seenDropEventIDs: [:]
|
||||
))
|
||||
|
||||
let fixture = Fixture(
|
||||
now: { date },
|
||||
dedupStore: BridgeDropDedupStore(fileURL: fileURL)
|
||||
)
|
||||
fixture.sealResult = makeEnvelope(recipientKey: recipientKey)
|
||||
var results: [Bool] = []
|
||||
fixture.service.depositDrop(
|
||||
content: "legacy",
|
||||
messageID: messageID,
|
||||
recipientNoiseKey: recipientKey
|
||||
) { results.append($0) }
|
||||
#expect(results == [false])
|
||||
#expect(fixture.sealRequests.isEmpty)
|
||||
|
||||
date = date.addingTimeInterval(CourierEnvelope.maxLifetimeSeconds + 1)
|
||||
fixture.service.depositDrop(
|
||||
content: "after expiry",
|
||||
messageID: messageID,
|
||||
recipientNoiseKey: recipientKey
|
||||
) { results.append($0) }
|
||||
#expect(results == [false, true])
|
||||
#expect(fixture.publishedEvents.count == 1)
|
||||
fixture.service.flushDedupSnapshot()
|
||||
|
||||
let snapshot = BridgeDropDedupStore(fileURL: fileURL).load()
|
||||
#expect(snapshot.publishedDropKeys[messageID] == nil)
|
||||
#expect(snapshot.publishedDropKeys.count == 1)
|
||||
}
|
||||
|
||||
@Test func panicWipeInvalidatesInFlightPublishCompletion() throws {
|
||||
let fileURL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("bridge-dedup-\(UUID().uuidString).json")
|
||||
@@ -297,8 +425,10 @@ struct BridgeCourierServiceTests {
|
||||
#expect(firstResults == [false])
|
||||
|
||||
// The evicted first drop is deposit-able again (slot released).
|
||||
let sealCountBeforeRetry = fixture.sealRequests.count
|
||||
fixture.service.depositDrop(content: "0-retry", messageID: firstID, recipientNoiseKey: key)
|
||||
#expect(fixture.service.pendingDrops.last?.dedupKey == firstID)
|
||||
#expect(fixture.sealRequests.count == sealCountBeforeRetry + 1)
|
||||
#expect(fixture.service.pendingDrops.count == BridgeCourierService.Limits.maxPendingDrops)
|
||||
}
|
||||
|
||||
@Test func oversizeDropConsumesSlotInsteadOfChurning() {
|
||||
|
||||
@@ -15,7 +15,7 @@ final class FavoritesPersistenceServiceTests: XCTestCase {
|
||||
|
||||
service.addFavorite(peerNoisePublicKey: peerKey, peerNostrPublicKey: "npub1alice", peerNickname: "Alice")
|
||||
|
||||
wait(for: [expectation], timeout: 1.0)
|
||||
wait(for: [expectation], timeout: TestConstants.settleTimeout)
|
||||
XCTAssertTrue(service.isFavorite(peerKey))
|
||||
XCTAssertEqual(service.getFavoriteStatus(for: peerKey)?.peerNickname, "Alice")
|
||||
XCTAssertNotNil(keychain.load(key: storageKey, service: serviceKey))
|
||||
|
||||
@@ -227,7 +227,7 @@ final class GeohashPresenceServiceTests: XCTestCase {
|
||||
}
|
||||
|
||||
private func waitUntil(
|
||||
timeout: TimeInterval = 1.0,
|
||||
timeout: TimeInterval = TestConstants.settleTimeout,
|
||||
condition: @escaping @MainActor () -> Bool
|
||||
) async -> Bool {
|
||||
let deadline = Date().addingTimeInterval(timeout)
|
||||
|
||||
@@ -355,7 +355,7 @@ final class LocationStateManagerTests: XCTestCase {
|
||||
}
|
||||
|
||||
private func waitUntil(
|
||||
timeout: TimeInterval = 1.0,
|
||||
timeout: TimeInterval = TestConstants.settleTimeout,
|
||||
condition: @escaping @MainActor () -> Bool
|
||||
) async -> Bool {
|
||||
let deadline = Date().addingTimeInterval(timeout)
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
import Foundation
|
||||
import Testing
|
||||
@testable import bitchat
|
||||
|
||||
/// Media used to be bounded only by a 100 MB incoming quota, so a received
|
||||
/// photo or a sent voice note could sit on disk indefinitely — outliving the
|
||||
/// conversation it belonged to, which is exactly what a seized device gives up.
|
||||
/// These cover the age-based sweep that bounds it in time as well.
|
||||
struct MediaRetentionTests {
|
||||
private func makeRoot() -> URL {
|
||||
FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("media-retention-\(UUID().uuidString)", isDirectory: true)
|
||||
}
|
||||
|
||||
private func write(
|
||||
_ name: String,
|
||||
in directory: URL,
|
||||
modified: Date
|
||||
) throws -> URL {
|
||||
try FileManager.default.createDirectory(
|
||||
at: directory,
|
||||
withIntermediateDirectories: true
|
||||
)
|
||||
let url = directory.appendingPathComponent(name)
|
||||
try Data([0xFF, 0xD8, 0xFF, 0xD9]).write(to: url)
|
||||
try FileManager.default.setAttributes(
|
||||
[.modificationDate: modified],
|
||||
ofItemAtPath: url.path
|
||||
)
|
||||
return url
|
||||
}
|
||||
|
||||
@Test
|
||||
func expiresOutgoingMediaPastRetentionAndKeepsFreshMedia() throws {
|
||||
let root = makeRoot()
|
||||
defer { try? FileManager.default.removeItem(at: root) }
|
||||
let store = BLEIncomingFileStore(baseDirectory: root)
|
||||
let outgoing = root.appendingPathComponent("files/images/outgoing", isDirectory: true)
|
||||
|
||||
// Outgoing media had no lifetime at all before this sweep: the quota
|
||||
// only ever considered incoming directories.
|
||||
let stale = try write(
|
||||
"sent_old.jpg",
|
||||
in: outgoing,
|
||||
modified: Date(timeIntervalSinceNow: -8 * 24 * 60 * 60)
|
||||
)
|
||||
let fresh = try write(
|
||||
"sent_new.jpg",
|
||||
in: outgoing,
|
||||
modified: Date(timeIntervalSinceNow: -60)
|
||||
)
|
||||
|
||||
let removed = store.expireAgedMedia()
|
||||
|
||||
#expect(removed == 1)
|
||||
#expect(!FileManager.default.fileExists(atPath: stale.path))
|
||||
#expect(FileManager.default.fileExists(atPath: fresh.path))
|
||||
}
|
||||
|
||||
@Test
|
||||
func expiresIncomingMediaPastRetention() throws {
|
||||
let root = makeRoot()
|
||||
defer { try? FileManager.default.removeItem(at: root) }
|
||||
let store = BLEIncomingFileStore(baseDirectory: root)
|
||||
let incoming = try store.incomingDirectory(subdirectory: "voicenotes/incoming")
|
||||
|
||||
let stale = try write(
|
||||
"received.m4a",
|
||||
in: incoming,
|
||||
modified: Date(timeIntervalSinceNow: -8 * 24 * 60 * 60)
|
||||
)
|
||||
|
||||
#expect(store.expireAgedMedia() == 1)
|
||||
#expect(!FileManager.default.fileExists(atPath: stale.path))
|
||||
}
|
||||
|
||||
@Test
|
||||
func retentionSweepSkipsInFlightLiveCaptures() throws {
|
||||
let root = makeRoot()
|
||||
defer { try? FileManager.default.removeItem(at: root) }
|
||||
let store = BLEIncomingFileStore(baseDirectory: root)
|
||||
let incoming = try store.incomingDirectory(subdirectory: "voicenotes/incoming")
|
||||
|
||||
// Deleting a live capture mid-stream unlinks the inode under the
|
||||
// coordinator's open FileHandle, so age must not override the guard.
|
||||
let inFlight = try write(
|
||||
"\(BLEIncomingFileStore.liveCapturePrefix)00112233445566ff_dm.aac",
|
||||
in: incoming,
|
||||
modified: Date(timeIntervalSinceNow: -30 * 24 * 60 * 60)
|
||||
)
|
||||
|
||||
#expect(store.expireAgedMedia() == 0)
|
||||
#expect(FileManager.default.fileExists(atPath: inFlight.path))
|
||||
}
|
||||
|
||||
@Test
|
||||
func nonPositiveRetentionIsANoOp() throws {
|
||||
let root = makeRoot()
|
||||
defer { try? FileManager.default.removeItem(at: root) }
|
||||
let store = BLEIncomingFileStore(baseDirectory: root)
|
||||
let incoming = try store.incomingDirectory(subdirectory: "images/incoming")
|
||||
|
||||
let file = try write(
|
||||
"received.jpg",
|
||||
in: incoming,
|
||||
modified: Date(timeIntervalSinceNow: -365 * 24 * 60 * 60)
|
||||
)
|
||||
|
||||
#expect(store.expireAgedMedia(retention: 0) == 0)
|
||||
#expect(FileManager.default.fileExists(atPath: file.path))
|
||||
}
|
||||
|
||||
@Test
|
||||
func defaultRetentionIsSevenDays() {
|
||||
#expect(BLEIncomingFileStore.defaultMediaRetention == 7 * 24 * 60 * 60)
|
||||
}
|
||||
}
|
||||
@@ -207,6 +207,42 @@ struct MessageOutboxStoreTests {
|
||||
#expect(MessageOutboxStore(keychain: keychain, fileURL: fileURL).load().isEmpty)
|
||||
}
|
||||
|
||||
@Test func deferredScopedRemovalTombstoneFiltersOnlySelectedPeer() {
|
||||
let fileURL = makeTempURL()
|
||||
defer { try? FileManager.default.removeItem(at: fileURL) }
|
||||
let keychain = MockKeychain()
|
||||
let acknowledgedPeer = PeerID(str: "0000000000000001")
|
||||
let otherPeer = PeerID(str: "0000000000000002")
|
||||
MessageOutboxStore(keychain: keychain, fileURL: fileURL).save([
|
||||
acknowledgedPeer: [makeMessage("shared-id", content: "for acknowledged peer")],
|
||||
otherPeer: [makeMessage("shared-id", content: "for other peer")]
|
||||
])
|
||||
|
||||
var protectedDataUnavailable = true
|
||||
let restored = MessageOutboxStore(
|
||||
keychain: keychain,
|
||||
fileURL: fileURL,
|
||||
readData: { url in
|
||||
if protectedDataUnavailable {
|
||||
throw NSError(domain: NSCocoaErrorDomain, code: NSFileReadNoPermissionError)
|
||||
}
|
||||
return try Data(contentsOf: url)
|
||||
}
|
||||
)
|
||||
#expect(restored.load().isEmpty)
|
||||
restored.recordRemoval(messageID: "shared-id", for: [acknowledgedPeer])
|
||||
restored.save([:])
|
||||
|
||||
protectedDataUnavailable = false
|
||||
let recovered = restored.retryDeferredLoad()
|
||||
#expect(recovered?[acknowledgedPeer] == nil)
|
||||
#expect(recovered?[otherPeer]?.map(\.messageID) == ["shared-id"])
|
||||
|
||||
let relaunched = MessageOutboxStore(keychain: keychain, fileURL: fileURL).load()
|
||||
#expect(relaunched[acknowledgedPeer] == nil)
|
||||
#expect(relaunched[otherPeer]?.map(\.messageID) == ["shared-id"])
|
||||
}
|
||||
|
||||
@Test func wipeRemovesFileAndKey() {
|
||||
let fileURL = makeTempURL()
|
||||
let keychain = MockKeychain()
|
||||
|
||||
@@ -79,18 +79,231 @@ struct MessageRouterTests {
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func sendPrivate_connectedSendIsNotRetained() async {
|
||||
func peerBoundDeliveryAckCannotClearAnotherPeersRetainedMessage() async {
|
||||
let intendedPeer = PeerID(str: "0000000000000023")
|
||||
let otherPeer = PeerID(str: "0000000000000024")
|
||||
let transport = MockTransport()
|
||||
transport.reachablePeers = [intendedPeer, otherPeer]
|
||||
|
||||
let router = MessageRouter(transports: [transport])
|
||||
router.sendPrivate(
|
||||
"Secret",
|
||||
to: intendedPeer,
|
||||
recipientNickname: "Intended",
|
||||
messageID: "peer-bound-ack"
|
||||
)
|
||||
#expect(transport.sentPrivateMessages.count == 1)
|
||||
|
||||
// Even a receipt arriving over another authenticated conversation
|
||||
// must not terminalize the intended peer's retained retry.
|
||||
router.markDelivered("peer-bound-ack", from: [otherPeer])
|
||||
router.flushOutbox(for: intendedPeer)
|
||||
#expect(transport.sentPrivateMessages.count == 2)
|
||||
|
||||
router.markDelivered("peer-bound-ack", from: [intendedPeer])
|
||||
router.flushOutbox(for: intendedPeer)
|
||||
#expect(transport.sentPrivateMessages.count == 2)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func sendPrivate_connectedSecureSendRetainsUntilDeliveryAck() async {
|
||||
let peerID = PeerID(str: "0000000000000007")
|
||||
let transport = MockTransport()
|
||||
transport.connectedPeers.insert(peerID)
|
||||
transport.reachablePeers.insert(peerID)
|
||||
transport.securePeers = [peerID]
|
||||
|
||||
let router = MessageRouter(transports: [transport])
|
||||
router.sendPrivate("Hello", to: peerID, recipientNickname: "Peer", messageID: "m7")
|
||||
#expect(transport.sentPrivateMessages.count == 1)
|
||||
|
||||
router.flushOutbox(for: peerID)
|
||||
// A newly authenticated/replacement session retries the retained
|
||||
// message instead of losing the first ciphertext to a stale session.
|
||||
router.retrySecurePrivateMessagesAfterAuthentication(for: [peerID])
|
||||
#expect(transport.sentPrivateMessages.count == 2)
|
||||
|
||||
router.markDelivered("m7")
|
||||
router.retrySecurePrivateMessagesAfterAuthentication(for: [peerID])
|
||||
#expect(transport.sentPrivateMessages.count == 2)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func authenticationRetry_matchesStableOutboxAliasWithoutDoubleSending() async {
|
||||
let shortPeerID = PeerID(str: "0000000000000019")
|
||||
let stablePeerID = PeerID(hexData: Data(repeating: 0x19, count: 32))
|
||||
let transport = MockTransport()
|
||||
transport.connectedPeers.insert(stablePeerID)
|
||||
transport.securePeers = [stablePeerID]
|
||||
|
||||
let router = MessageRouter(transports: [transport])
|
||||
router.sendPrivate("Hello", to: stablePeerID, recipientNickname: "Peer", messageID: "alias-retry")
|
||||
|
||||
router.retrySecurePrivateMessagesAfterAuthentication(for: [shortPeerID, stablePeerID, stablePeerID])
|
||||
|
||||
#expect(transport.sentPrivateMessages.map(\.messageID) == ["alias-retry", "alias-retry"])
|
||||
#expect(transport.sentPrivateMessages.allSatisfy { $0.peerID == stablePeerID })
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func authenticationRetry_preservesFIFOAcrossSplitAliases() async {
|
||||
let shortPeerID = PeerID(str: "0000000000000022")
|
||||
let stablePeerID = PeerID(hexData: Data(repeating: 0x22, count: 32))
|
||||
let transport = MockTransport()
|
||||
transport.connectedPeers = [shortPeerID, stablePeerID]
|
||||
transport.securePeers = [shortPeerID, stablePeerID]
|
||||
let clock = MutableTestClock()
|
||||
let router = MessageRouter(transports: [transport], now: { clock.now })
|
||||
|
||||
// The older message lives under the stable key, even though the auth
|
||||
// callback supplies the ephemeral alias first.
|
||||
router.sendPrivate("Older", to: stablePeerID, recipientNickname: "Peer", messageID: "fifo-old")
|
||||
clock.now = clock.now.addingTimeInterval(1)
|
||||
router.sendPrivate("Newer", to: shortPeerID, recipientNickname: "Peer", messageID: "fifo-new")
|
||||
transport.resetRecordings()
|
||||
|
||||
router.retrySecurePrivateMessagesAfterAuthentication(for: [shortPeerID, stablePeerID])
|
||||
|
||||
#expect(transport.sentPrivateMessages.map(\.messageID) == ["fifo-old", "fifo-new"])
|
||||
#expect(transport.sentPrivateMessages.map(\.peerID) == [stablePeerID, shortPeerID])
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func authenticationRetry_doesNotDuplicateNormalPendingHandshakeSend() async {
|
||||
let peerID = PeerID(str: "0000000000000020")
|
||||
let transport = MockTransport()
|
||||
transport.connectedPeers.insert(peerID)
|
||||
transport.securePeers = []
|
||||
|
||||
let router = MessageRouter(transports: [transport])
|
||||
router.sendPrivate("Hello", to: peerID, recipientNickname: "Peer", messageID: "normal-handshake")
|
||||
#expect(transport.sentPrivateMessages.count == 1)
|
||||
|
||||
// BLE owns this pending send and drains it after authentication. Once
|
||||
// the session becomes secure, the router's targeted auth retry must
|
||||
// stay silent instead of producing a second copy.
|
||||
transport.securePeers = [peerID]
|
||||
router.retrySecurePrivateMessagesAfterAuthentication(for: [peerID])
|
||||
#expect(transport.sentPrivateMessages.count == 1)
|
||||
|
||||
router.markDelivered("normal-handshake")
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func authenticationRetry_scopesCollidingMessageIDsByPeer() async {
|
||||
let securePeer = PeerID(str: "0000000000000025")
|
||||
let pendingPeer = PeerID(str: "0000000000000026")
|
||||
let transport = MockTransport()
|
||||
transport.connectedPeers = [securePeer, pendingPeer]
|
||||
transport.securePeers = [securePeer]
|
||||
|
||||
let router = MessageRouter(transports: [transport])
|
||||
let promotedID = "collision-promoted"
|
||||
let clearedID = "collision-cleared"
|
||||
|
||||
// Pending B then secure A: an ID-global marker falsely promotes B.
|
||||
router.sendPrivate(
|
||||
"pending promoted",
|
||||
to: pendingPeer,
|
||||
recipientNickname: "Pending",
|
||||
messageID: promotedID
|
||||
)
|
||||
router.sendPrivate(
|
||||
"secure promoted",
|
||||
to: securePeer,
|
||||
recipientNickname: "Secure",
|
||||
messageID: promotedID
|
||||
)
|
||||
|
||||
// Secure A then pending B: an ID-global removal falsely clears A.
|
||||
router.sendPrivate(
|
||||
"secure cleared",
|
||||
to: securePeer,
|
||||
recipientNickname: "Secure",
|
||||
messageID: clearedID
|
||||
)
|
||||
router.sendPrivate(
|
||||
"pending cleared",
|
||||
to: pendingPeer,
|
||||
recipientNickname: "Pending",
|
||||
messageID: clearedID
|
||||
)
|
||||
|
||||
transport.resetRecordings()
|
||||
transport.securePeers = [securePeer, pendingPeer]
|
||||
|
||||
router.retrySecurePrivateMessagesAfterAuthentication(for: [pendingPeer])
|
||||
#expect(transport.sentPrivateMessages.isEmpty)
|
||||
|
||||
router.retrySecurePrivateMessagesAfterAuthentication(for: [securePeer])
|
||||
#expect(transport.sentPrivateMessages.count == 2)
|
||||
#expect(Set(transport.sentPrivateMessages.map(\.messageID)) == [promotedID, clearedID])
|
||||
#expect(transport.sentPrivateMessages.allSatisfy { $0.peerID == securePeer })
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func authenticationRetry_doesNotDuplicateMessageRequeuedByBLEForHandshake() async {
|
||||
let peerID = PeerID(str: "0000000000000021")
|
||||
let transport = MockTransport()
|
||||
transport.connectedPeers.insert(peerID)
|
||||
transport.securePeers = [peerID]
|
||||
|
||||
let router = MessageRouter(transports: [transport])
|
||||
router.sendPrivate("Hello", to: peerID, recipientNickname: "Peer", messageID: "session-lost")
|
||||
#expect(transport.sentPrivateMessages.count == 1)
|
||||
|
||||
// The session disappears before a normal outbox flush. That send is
|
||||
// now owned by BLE's pending-handshake queue, so it clears the
|
||||
// router's secure-auth retry marker.
|
||||
transport.securePeers = []
|
||||
router.flushOutbox(for: peerID)
|
||||
#expect(transport.sentPrivateMessages.count == 2)
|
||||
|
||||
transport.securePeers = [peerID]
|
||||
router.retrySecurePrivateMessagesAfterAuthentication(for: [peerID])
|
||||
#expect(transport.sentPrivateMessages.count == 2)
|
||||
|
||||
router.markDelivered("session-lost")
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func sendPrivate_fastDeliveryAckCannotRaceAheadOfRetention() async {
|
||||
let peerID = PeerID(str: "0000000000000017")
|
||||
let transport = MockTransport()
|
||||
transport.connectedPeers.insert(peerID)
|
||||
transport.securePeers = [peerID]
|
||||
|
||||
let router = MessageRouter(transports: [transport])
|
||||
transport.onSendPrivateMessage = { messageID in
|
||||
router.markDelivered(messageID)
|
||||
}
|
||||
|
||||
router.sendPrivate("Hello", to: peerID, recipientNickname: "Peer", messageID: "fast-ack")
|
||||
#expect(transport.sentPrivateMessages.map(\.messageID) == ["fast-ack"])
|
||||
|
||||
transport.onSendPrivateMessage = nil
|
||||
router.flushOutbox(for: peerID)
|
||||
#expect(transport.sentPrivateMessages.map(\.messageID) == ["fast-ack"])
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func flushOutbox_synchronousAckDoesNotResurrectSnapshotEntry() async {
|
||||
let peerID = PeerID(str: "0000000000000018")
|
||||
let transport = MockTransport()
|
||||
transport.connectedPeers.insert(peerID)
|
||||
transport.securePeers = [peerID]
|
||||
|
||||
let router = MessageRouter(transports: [transport])
|
||||
router.sendPrivate("Hello", to: peerID, recipientNickname: "Peer", messageID: "flush-fast-ack")
|
||||
transport.onSendPrivateMessage = { messageID in
|
||||
router.markDelivered(messageID)
|
||||
}
|
||||
|
||||
router.flushOutbox(for: peerID)
|
||||
#expect(transport.sentPrivateMessages.count == 2)
|
||||
|
||||
transport.onSendPrivateMessage = nil
|
||||
router.flushOutbox(for: peerID)
|
||||
#expect(transport.sentPrivateMessages.count == 2)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
@@ -392,10 +605,31 @@ struct MessageRouterTests {
|
||||
#expect(transport.sentPrivateMessages.count == 11)
|
||||
}
|
||||
|
||||
/// With an established secure session the connected fast-path stays
|
||||
/// exactly as before: trusted outright, no retained copy, no courier.
|
||||
@Test @MainActor
|
||||
func sendPrivate_connectedWithSecureSessionIsTrustedOutright() async {
|
||||
func authenticationRetry_capsActualSecureTransmissions() async {
|
||||
let peerID = PeerID(str: "00000000000000ad")
|
||||
let transport = MockTransport()
|
||||
transport.connectedPeers.insert(peerID)
|
||||
transport.securePeers = [peerID]
|
||||
|
||||
let router = MessageRouter(transports: [transport])
|
||||
var dropped: [String] = []
|
||||
router.onMessageDropped = { messageID, _ in dropped.append(messageID) }
|
||||
|
||||
router.sendPrivate("Hello", to: peerID, recipientNickname: "Peer", messageID: "secure-retry")
|
||||
for _ in 0..<10 {
|
||||
router.retrySecurePrivateMessagesAfterAuthentication(for: [peerID])
|
||||
}
|
||||
|
||||
#expect(dropped == ["secure-retry"])
|
||||
#expect(transport.sentPrivateMessages.count == 8)
|
||||
}
|
||||
|
||||
/// With an established secure session the connected fast-path sends
|
||||
/// immediately and never leaks to couriers, but retains a local encrypted
|
||||
/// outbox copy until the peer confirms receipt.
|
||||
@Test @MainActor
|
||||
func sendPrivate_connectedWithSecureSessionRetainsLocallyWithoutCourier() async {
|
||||
let peerID = PeerID(str: "00000000000000ab")
|
||||
let peerKey = Data(repeating: 0xAB, count: 32)
|
||||
let courier = PeerID(str: "00000000000000cc")
|
||||
@@ -415,7 +649,11 @@ struct MessageRouterTests {
|
||||
#expect(transport.sentPrivateMessages.map(\.messageID) == ["cs2"])
|
||||
#expect(transport.sentCourierMessages.isEmpty)
|
||||
router.flushOutbox(for: peerID)
|
||||
#expect(transport.sentPrivateMessages.count == 1)
|
||||
#expect(transport.sentPrivateMessages.count == 2)
|
||||
#expect(transport.sentCourierMessages.isEmpty)
|
||||
router.markDelivered("cs2")
|
||||
router.flushOutbox(for: peerID)
|
||||
#expect(transport.sentPrivateMessages.count == 2)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
@@ -527,6 +765,52 @@ struct MessageRouterTests {
|
||||
#expect(carried == ["bridge-ack"])
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func bridgeDepositsScopeCollidingMessageIDsByRecipient() async {
|
||||
let firstRecipient = PeerID(str: "00000000000000b1")
|
||||
let secondRecipient = PeerID(str: "00000000000000b2")
|
||||
let firstKey = Data(repeating: 0xB1, count: 32)
|
||||
let secondKey = Data(repeating: 0xB2, count: 32)
|
||||
let recipientKeys = [
|
||||
firstRecipient: firstKey,
|
||||
secondRecipient: secondKey
|
||||
]
|
||||
let router = MessageRouter(
|
||||
transports: [MockTransport()],
|
||||
courierDirectory: CourierDirectory(
|
||||
noiseKey: { recipientKeys[$0] },
|
||||
isTrustedCourier: { _ in false }
|
||||
)
|
||||
)
|
||||
var requestedKeys: [Data] = []
|
||||
var completions: [@MainActor (Bool) -> Void] = []
|
||||
router.bridgeCourierDeposit = { _, _, recipientKey, completion in
|
||||
requestedKeys.append(recipientKey)
|
||||
completions.append(completion)
|
||||
}
|
||||
var carriedPeers: [PeerID] = []
|
||||
router.onMessageCarried = { _, peerID in carriedPeers.append(peerID) }
|
||||
|
||||
router.sendPrivate(
|
||||
"First",
|
||||
to: firstRecipient,
|
||||
recipientNickname: "First",
|
||||
messageID: "bridge-collision"
|
||||
)
|
||||
router.sendPrivate(
|
||||
"Second",
|
||||
to: secondRecipient,
|
||||
recipientNickname: "Second",
|
||||
messageID: "bridge-collision"
|
||||
)
|
||||
|
||||
#expect(completions.count == 2)
|
||||
#expect(Set(requestedKeys) == [firstKey, secondKey])
|
||||
|
||||
completions.forEach { $0(true) }
|
||||
#expect(Set(carriedPeers) == [firstRecipient, secondRecipient])
|
||||
}
|
||||
|
||||
// MARK: - Outbox persistence
|
||||
|
||||
@Test @MainActor
|
||||
@@ -582,6 +866,82 @@ struct MessageRouterTests {
|
||||
#expect(transport2.sentPrivateMessages.isEmpty)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func scopedDeliveryAckClearsOnlySelectedPeerWhenMessageIDsCollide() async {
|
||||
let fileURL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("router-outbox-scoped-ack-\(UUID().uuidString).sealed")
|
||||
defer { try? FileManager.default.removeItem(at: fileURL) }
|
||||
let keychain = MockKeychain()
|
||||
let acknowledgedPeer = PeerID(str: "00000000000000d1")
|
||||
let otherPeer = PeerID(str: "00000000000000d2")
|
||||
let transport = MockTransport()
|
||||
let router = MessageRouter(
|
||||
transports: [transport],
|
||||
outboxStore: MessageOutboxStore(keychain: keychain, fileURL: fileURL)
|
||||
)
|
||||
router.sendPrivate("For acknowledged peer", to: acknowledgedPeer, recipientNickname: "One", messageID: "shared-id")
|
||||
router.sendPrivate("For other peer", to: otherPeer, recipientNickname: "Two", messageID: "shared-id")
|
||||
|
||||
#expect(router.markDelivered("shared-id", for: [acknowledgedPeer]))
|
||||
transport.reachablePeers.formUnion([acknowledgedPeer, otherPeer])
|
||||
router.flushOutbox(for: acknowledgedPeer)
|
||||
router.flushOutbox(for: otherPeer)
|
||||
|
||||
#expect(transport.sentPrivateMessages.map(\.peerID) == [otherPeer])
|
||||
let persisted = MessageOutboxStore(keychain: keychain, fileURL: fileURL).load()
|
||||
#expect(persisted[acknowledgedPeer] == nil)
|
||||
#expect(persisted[otherPeer]?.map(\.messageID) == ["shared-id"])
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func scopedAckWhileColdLoadIsLockedPreventsOnlyTargetPeerResurrection() async {
|
||||
let fileURL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("router-locked-scoped-ack-\(UUID().uuidString).sealed")
|
||||
defer { try? FileManager.default.removeItem(at: fileURL) }
|
||||
let keychain = MockKeychain()
|
||||
let acknowledgedPeer = PeerID(str: "00000000000000d3")
|
||||
let otherPeer = PeerID(str: "00000000000000d4")
|
||||
let durable = MessageOutboxStore.QueuedMessage(
|
||||
content: "Queued before reboot",
|
||||
nickname: "Peer",
|
||||
messageID: "shared-locked-id",
|
||||
timestamp: Date()
|
||||
)
|
||||
MessageOutboxStore(keychain: keychain, fileURL: fileURL).save([
|
||||
acknowledgedPeer: [durable],
|
||||
otherPeer: [durable]
|
||||
])
|
||||
|
||||
var protectedDataUnavailable = true
|
||||
let restoredStore = MessageOutboxStore(
|
||||
keychain: keychain,
|
||||
fileURL: fileURL,
|
||||
readData: { url in
|
||||
if protectedDataUnavailable {
|
||||
throw NSError(domain: NSCocoaErrorDomain, code: NSFileReadNoPermissionError)
|
||||
}
|
||||
return try Data(contentsOf: url)
|
||||
}
|
||||
)
|
||||
let transport = MockTransport()
|
||||
transport.reachablePeers.formUnion([acknowledgedPeer, otherPeer])
|
||||
let router = MessageRouter(transports: [transport], outboxStore: restoredStore)
|
||||
|
||||
router.markDelivered(
|
||||
"shared-locked-id",
|
||||
from: [acknowledgedPeer]
|
||||
)
|
||||
protectedDataUnavailable = false
|
||||
restoredStore.retryDeferredLoad()
|
||||
await Task.yield()
|
||||
await Task.yield()
|
||||
|
||||
#expect(transport.sentPrivateMessages.map(\.peerID) == [otherPeer])
|
||||
let persisted = MessageOutboxStore(keychain: keychain, fileURL: fileURL).load()
|
||||
#expect(persisted[acknowledgedPeer] == nil)
|
||||
#expect(persisted[otherPeer]?.map(\.messageID) == ["shared-locked-id"])
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func protectedDataRecoveryMergesDurableAndLockedWakeMessagesIntoRouter() async {
|
||||
let fileURL = FileManager.default.temporaryDirectory
|
||||
@@ -780,12 +1140,14 @@ struct MessageRouterTests {
|
||||
protectedDataUnavailable = false
|
||||
restoredStore.retryDeferredLoad() // captures unseen durable + known wake
|
||||
|
||||
// Secure direct flush removes the wake message before recovery's
|
||||
// MainActor merge. It must remain removed, while the unseen durable
|
||||
// message still arrives through the pending recovery claim.
|
||||
// A secure direct retry followed by its delivery ack removes the wake
|
||||
// message before recovery's MainActor merge. It must remain removed,
|
||||
// while the unseen durable message still arrives through the pending
|
||||
// recovery claim.
|
||||
transport.connectedPeers.insert(peerID)
|
||||
transport.securePeers = [peerID]
|
||||
router.flushOutbox(for: peerID)
|
||||
router.markDelivered("recovery-gap-known")
|
||||
await Task.yield()
|
||||
await Task.yield()
|
||||
|
||||
@@ -856,7 +1218,8 @@ struct MessageRouterTests {
|
||||
restoredStore.retryDeferredLoad() // persists D+W and queues recovery
|
||||
transport.connectedPeers.insert(peerID)
|
||||
transport.securePeers = [peerID]
|
||||
router.flushOutbox(for: peerID) // removes W before queued callback
|
||||
router.flushOutbox(for: peerID)
|
||||
router.markDelivered("recovery-write-failure-known") // removes W before queued callback
|
||||
|
||||
// The gap save may remove W, but it must leave unseen D durable until
|
||||
// MessageRouter receives the pending recovery callback.
|
||||
|
||||
@@ -63,7 +63,7 @@ final class NetworkActivationServiceTests: XCTestCase {
|
||||
context.service.start()
|
||||
context.service.setUserTorEnabled(false)
|
||||
|
||||
wait(for: [notified], timeout: 1.0)
|
||||
wait(for: [notified], timeout: TestConstants.negativeWaitWindow)
|
||||
context.notificationCenter.removeObserver(token)
|
||||
|
||||
XCTAssertFalse(context.service.userTorEnabled)
|
||||
@@ -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,
|
||||
@@ -178,7 +243,7 @@ final class NetworkActivationServiceTests: XCTestCase {
|
||||
}
|
||||
|
||||
private func waitUntil(
|
||||
timeout: TimeInterval = 1.0,
|
||||
timeout: TimeInterval = TestConstants.settleTimeout,
|
||||
condition: @escaping @MainActor () -> Bool
|
||||
) async -> Bool {
|
||||
let deadline = Date().addingTimeInterval(timeout)
|
||||
|
||||
@@ -69,25 +69,45 @@ final class NetworkReachabilityGateTests: XCTestCase {
|
||||
XCTAssertNil(d.pendingRemaining(at: t0.addingTimeInterval(2.5)))
|
||||
}
|
||||
|
||||
func test_monitor_duplicateUpdatesDoNotPostponeOfflineCommit() async {
|
||||
let monitor = NWPathReachabilityMonitor(debounceInterval: 1.0)
|
||||
/// Wiring only: a duplicate mid-window still yields exactly one committed
|
||||
/// `false`, published through the monitor's debounce.
|
||||
///
|
||||
/// This deliberately makes no assertion about *when* the flush fires. It
|
||||
/// used to bound elapsed wall-clock time at 1.4 s to prove the deadline was
|
||||
/// not restarted, which flaked on loaded CI runners — one observed run took
|
||||
/// 3.75 s, because `Task.sleep` and the `asyncAfter` flush are both real
|
||||
/// time and neither is bounded above on a busy machine. No wall-clock bound
|
||||
/// can distinguish "deadline preserved" from "runner is slow", so the timing
|
||||
/// property is asserted where it is computable instead:
|
||||
/// `test_debounce_duplicateObservationsPreservePendingDeadline` drives
|
||||
/// `ReachabilityDebounce` with injected timestamps and checks
|
||||
/// `pendingRemaining` directly.
|
||||
///
|
||||
/// The clock is injected here so the debounce arithmetic is deterministic
|
||||
/// even though the flush itself is scheduled in real time.
|
||||
func test_monitor_duplicateUpdatesCommitOnceThroughTheDebounce() async {
|
||||
let clock = MutableDate(now: Date(timeIntervalSince1970: 1_784_000_000))
|
||||
let monitor = NWPathReachabilityMonitor(
|
||||
debounceInterval: 0.2,
|
||||
now: { clock.now }
|
||||
)
|
||||
var received: [Bool] = []
|
||||
let cancellable = monitor.reachabilityPublisher.sink { received.append($0) }
|
||||
defer { cancellable.cancel() }
|
||||
|
||||
let start = Date()
|
||||
monitor.ingest(reachable: false)
|
||||
try? await Task.sleep(nanoseconds: 500_000_000)
|
||||
// Duplicate unsatisfied update mid-window (e.g. interface detail change
|
||||
// while still offline) must not restart the debounce window.
|
||||
// Duplicate unsatisfied update mid-window (e.g. an interface detail
|
||||
// change while still offline).
|
||||
clock.now = clock.now.addingTimeInterval(0.1)
|
||||
monitor.ingest(reachable: false)
|
||||
// Past the original deadline, so the scheduled flush commits.
|
||||
clock.now = clock.now.addingTimeInterval(0.2)
|
||||
|
||||
let committed = await waitUntil(timeout: 2.0) { !received.isEmpty }
|
||||
// Generous: this is a liveness check, not a latency bound. A real
|
||||
// regression — never committing — still fails, just later.
|
||||
let committed = await waitUntil(timeout: 10.0) { !received.isEmpty }
|
||||
XCTAssertTrue(committed)
|
||||
XCTAssertEqual(received, [false])
|
||||
// The flush must fire at the original ~1.0s deadline, not ~1.5s
|
||||
// (a full interval after the duplicate).
|
||||
XCTAssertLessThan(Date().timeIntervalSince(start), 1.4)
|
||||
}
|
||||
|
||||
// MARK: - Service gating
|
||||
@@ -179,7 +199,7 @@ final class NetworkReachabilityGateTests: XCTestCase {
|
||||
}
|
||||
|
||||
private func waitUntil(
|
||||
timeout: TimeInterval = 1.0,
|
||||
timeout: TimeInterval = TestConstants.settleTimeout,
|
||||
condition: @escaping @MainActor () -> Bool
|
||||
) async -> Bool {
|
||||
let deadline = Date().addingTimeInterval(timeout)
|
||||
@@ -239,3 +259,13 @@ private final class GateMockProxyController: NetworkActivationProxyControlling {
|
||||
private(set) var proxyModes: [Bool] = []
|
||||
func setProxyMode(useTor: Bool) { proxyModes.append(useTor) }
|
||||
}
|
||||
|
||||
/// Controllable clock, so debounce arithmetic is deterministic even where the
|
||||
/// flush itself is scheduled in real time.
|
||||
private final class MutableDate: @unchecked Sendable {
|
||||
var now: Date
|
||||
|
||||
init(now: Date) {
|
||||
self.now = now
|
||||
}
|
||||
}
|
||||
|
||||
@@ -105,11 +105,11 @@ struct NoiseEncryptionServiceTests {
|
||||
|
||||
try establishSessions(alice: alice, bob: bob)
|
||||
|
||||
let authenticated = await TestHelpers.waitUntil({ recorder.count >= 2 }, timeout: 5.0)
|
||||
let authenticated = await TestHelpers.waitUntil({ recorder.count >= 2 }, timeout: TestConstants.settleTimeout)
|
||||
#expect(authenticated)
|
||||
let generationAuthenticated = await TestHelpers.waitUntil(
|
||||
{ recorder.generationCount >= 1 },
|
||||
timeout: 5.0
|
||||
timeout: TestConstants.settleTimeout
|
||||
)
|
||||
#expect(generationAuthenticated)
|
||||
#expect(alice.hasEstablishedSession(with: bobPeerID))
|
||||
@@ -166,7 +166,7 @@ struct NoiseEncryptionServiceTests {
|
||||
#expect(!receiver.hasSession(with: claimedAlicePeerID))
|
||||
let emittedAuthentication = await TestHelpers.waitUntil(
|
||||
{ recorder.count > 0 },
|
||||
timeout: TestConstants.shortTimeout
|
||||
timeout: TestConstants.negativeWaitWindow
|
||||
)
|
||||
#expect(!emittedAuthentication)
|
||||
}
|
||||
@@ -216,7 +216,7 @@ struct NoiseEncryptionServiceTests {
|
||||
#expect(try receiver.decrypt(after, from: alicePeerID) == Data("after".utf8))
|
||||
let emittedReplacementAuthentication = await TestHelpers.waitUntil(
|
||||
{ recorder.count > 1 },
|
||||
timeout: TestConstants.shortTimeout
|
||||
timeout: TestConstants.negativeWaitWindow
|
||||
)
|
||||
#expect(!emittedReplacementAuthentication)
|
||||
}
|
||||
@@ -652,12 +652,12 @@ struct NoiseEncryptionServiceTests {
|
||||
)
|
||||
let retried = await TestHelpers.waitUntil(
|
||||
{ recorder.messages.count == 1 },
|
||||
timeout: 1
|
||||
timeout: TestConstants.longTimeout
|
||||
)
|
||||
#expect(retried)
|
||||
let retryExpired = await TestHelpers.waitUntil(
|
||||
{ !service.hasSession(with: peerID) },
|
||||
timeout: 1
|
||||
timeout: TestConstants.longTimeout
|
||||
)
|
||||
#expect(retryExpired)
|
||||
#expect(recorder.timeoutCount == 1)
|
||||
@@ -710,7 +710,12 @@ struct NoiseEncryptionServiceTests {
|
||||
let alice = NoiseEncryptionService(keychain: MockKeychain())
|
||||
let bob = NoiseEncryptionService(
|
||||
keychain: MockKeychain(),
|
||||
ordinaryResponderHandshakeTimeout: 0.06,
|
||||
// Generous for the same reason as the quarantine-restore test
|
||||
// (#1483): this timeout also arms during the `establishSessions`
|
||||
// setup handshake below, where bob is the responder. At 0.06 a
|
||||
// preempted runner could fire it mid-setup, tear down the half-open
|
||||
// responder, and make message 3 be answered as a fresh initiation.
|
||||
ordinaryResponderHandshakeTimeout: 1.0,
|
||||
ordinaryReconnectRollbackCooldown: 0.3
|
||||
)
|
||||
let mallory = NoiseEncryptionService(keychain: MockKeychain())
|
||||
@@ -741,12 +746,12 @@ struct NoiseEncryptionServiceTests {
|
||||
|
||||
let restored = await TestHelpers.waitUntil(
|
||||
{ bob.hasEstablishedSession(with: alicePeerID) },
|
||||
timeout: 1
|
||||
timeout: TestConstants.longTimeout
|
||||
)
|
||||
#expect(restored)
|
||||
let callbackArrived = await TestHelpers.waitUntil(
|
||||
{ recovery.timeoutCount == 1 },
|
||||
timeout: 1
|
||||
timeout: TestConstants.longTimeout
|
||||
)
|
||||
#expect(callbackArrived)
|
||||
|
||||
@@ -780,7 +785,13 @@ struct NoiseEncryptionServiceTests {
|
||||
let bob = NoiseEncryptionService(
|
||||
keychain: MockKeychain(),
|
||||
ordinaryHandshakeTimeout: 0.04,
|
||||
ordinaryResponderHandshakeTimeout: 0.04
|
||||
// Also arms during the `establishSessions` setup handshake below,
|
||||
// where bob is the responder. Observed failing on a loaded CI
|
||||
// runner with exactly the signature #1483 documented: the setup's
|
||||
// `#expect(finalMessage == nil)` saw a 96-byte message 2, because
|
||||
// the half-open responder had already been torn down and message 3
|
||||
// was answered as a fresh initiation.
|
||||
ordinaryResponderHandshakeTimeout: 1.0
|
||||
)
|
||||
let alicePeerID = PeerID(publicKey: alice.getStaticPublicKeyData())
|
||||
let bobPeerID = PeerID(publicKey: bob.getStaticPublicKeyData())
|
||||
@@ -814,12 +825,12 @@ struct NoiseEncryptionServiceTests {
|
||||
// initiates one bounded convergence retry; drop that message 1 too.
|
||||
let retryPrepared = await TestHelpers.waitUntil(
|
||||
{ recovery.messages.count == 1 },
|
||||
timeout: 1
|
||||
timeout: TestConstants.longTimeout
|
||||
)
|
||||
#expect(retryPrepared)
|
||||
let retryExpired = await TestHelpers.waitUntil(
|
||||
{ !bob.hasSession(with: alicePeerID) },
|
||||
timeout: 1
|
||||
timeout: TestConstants.longTimeout
|
||||
)
|
||||
#expect(retryExpired)
|
||||
#expect(recovery.timeoutCount == 1)
|
||||
@@ -1026,7 +1037,7 @@ struct NoiseEncryptionServiceTests {
|
||||
|
||||
let requested = await TestHelpers.waitUntil(
|
||||
{ recovery.messages.count == 1 },
|
||||
timeout: 1
|
||||
timeout: TestConstants.longTimeout
|
||||
)
|
||||
#expect(requested)
|
||||
let retryMessage1 = try #require(recovery.messages.first)
|
||||
@@ -1235,9 +1246,17 @@ struct NoiseEncryptionServiceTests {
|
||||
@Test("Lost reconnect completion restores the quarantined transport")
|
||||
func timedOutReconnectRestoresQuarantinedTransport() async throws {
|
||||
let alice = NoiseEncryptionService(keychain: MockKeychain())
|
||||
// The injected responder timeout also arms during the ordinary setup
|
||||
// handshake below (bob is its responder), where the only work between
|
||||
// message 1 and message 3 is two consecutive synchronous statements.
|
||||
// It must be generous enough that a preempted runner cannot let the
|
||||
// timeout fire mid-setup and tear down the half-open responder — at
|
||||
// 20ms a loaded 2-core CI runner did exactly that, so message 3 was
|
||||
// answered as a fresh initiation (96-byte message 2) and nothing was
|
||||
// ever quarantined.
|
||||
let bob = NoiseEncryptionService(
|
||||
keychain: MockKeychain(),
|
||||
ordinaryResponderHandshakeTimeout: 0.02
|
||||
ordinaryResponderHandshakeTimeout: 1.0
|
||||
)
|
||||
let mallory = NoiseEncryptionService(keychain: MockKeychain())
|
||||
let alicePeerID = PeerID(publicKey: alice.getStaticPublicKeyData())
|
||||
@@ -1253,9 +1272,17 @@ struct NoiseEncryptionServiceTests {
|
||||
)
|
||||
#expect(!bob.hasEstablishedSession(with: alicePeerID))
|
||||
|
||||
try? await Task.sleep(nanoseconds: 100_000_000)
|
||||
|
||||
#expect(bob.hasEstablishedSession(with: alicePeerID))
|
||||
// Poll instead of sleeping a fixed interval: the responder timeout
|
||||
// fires on bob's manager queue at the quarantine deadline, and a
|
||||
// starved runner can delay that work item well past the deadline.
|
||||
let restored = await TestHelpers.waitUntil(
|
||||
{ bob.hasEstablishedSession(with: alicePeerID) },
|
||||
timeout: TestConstants.longTimeout
|
||||
)
|
||||
try #require(
|
||||
restored,
|
||||
"Responder timeout should restore the quarantined transport"
|
||||
)
|
||||
let oldTransport = try alice.encrypt(
|
||||
Data("timeout rollback".utf8),
|
||||
for: bobPeerID
|
||||
|
||||
@@ -44,6 +44,46 @@ final class NostrRelayManagerTests: XCTestCase {
|
||||
XCTAssertTrue(context.sessionFactory.allConnections.allSatisfy { $0.cancelCallCount >= 1 })
|
||||
}
|
||||
|
||||
/// A relay removed while its connection is queued behind Tor bootstrap
|
||||
/// must stay removed: draining the pending set used to resurrect it,
|
||||
/// because `dropRelays` never touched `pendingTorConnectionURLs` and a
|
||||
/// custom relay is in neither the default set nor the allow-list filter.
|
||||
func test_relayRemovedWhileWaitingForTor_staysRemovedWhenTorBecomesReady() async {
|
||||
let customURL = "wss://custom-removed.example"
|
||||
let center = NotificationCenter()
|
||||
let customRelays = MutableRelayList(urls: [customURL])
|
||||
let context = makeContext(
|
||||
permission: .authorized,
|
||||
userTorEnabled: true,
|
||||
torEnforced: true,
|
||||
torIsReady: false,
|
||||
notificationCenter: center,
|
||||
customRelays: customRelays
|
||||
)
|
||||
|
||||
// Defaults plus the custom relay all queue while Tor bootstraps.
|
||||
context.manager.connect()
|
||||
XCTAssertTrue(context.sessionFactory.requestedURLs.isEmpty)
|
||||
XCTAssertEqual(context.torWaiter.awaitCallCount, 1)
|
||||
|
||||
// The relay is removed by hand before Tor is ready.
|
||||
customRelays.urls = []
|
||||
center.post(name: NostrRelaySettings.didChangeNotification, object: nil)
|
||||
// The settings sink hops through the main queue; let it land.
|
||||
try? await Task.sleep(nanoseconds: 20_000_000)
|
||||
|
||||
context.torWaiter.resolve(true)
|
||||
|
||||
let defaultsConnected = await waitUntil {
|
||||
context.sessionFactory.requestedURLs.count == self.expectedDefaultRelayCount
|
||||
}
|
||||
XCTAssertTrue(defaultsConnected)
|
||||
XCTAssertFalse(
|
||||
context.sessionFactory.requestedURLs.contains(customURL),
|
||||
"a relay removed while Tor was bootstrapping must not reconnect when the pending queue drains"
|
||||
)
|
||||
}
|
||||
|
||||
func test_connect_waitsForTorReadinessBeforeCreatingSessions() async {
|
||||
let context = makeContext(permission: .authorized, userTorEnabled: true, torEnforced: true, torIsReady: false)
|
||||
|
||||
@@ -920,7 +960,7 @@ final class NostrRelayManagerTests: XCTestCase {
|
||||
try context.sessionFactory.latestConnection(for: relayURL)?.emitEventMessage(subscriptionID: "ordered", event: event)
|
||||
}
|
||||
|
||||
let allDelivered = await waitUntil(timeout: 5.0) {
|
||||
let allDelivered = await waitUntil(timeout: TestConstants.settleTimeout) {
|
||||
receivedIDs.count == events.count
|
||||
}
|
||||
XCTAssertTrue(allDelivered)
|
||||
@@ -966,7 +1006,7 @@ final class NostrRelayManagerTests: XCTestCase {
|
||||
}
|
||||
try context.sessionFactory.latestConnection(for: quietRelayURL)?.emitEventMessage(subscriptionID: "quiet", event: quietEvent)
|
||||
|
||||
let quietDelivered = await waitUntil(timeout: 5.0) { quietDeliveredAfterBusyCount >= 0 }
|
||||
let quietDelivered = await waitUntil(timeout: TestConstants.settleTimeout) { quietDeliveredAfterBusyCount >= 0 }
|
||||
XCTAssertTrue(quietDelivered, "relay B's event was never delivered")
|
||||
|
||||
// The signal: B did not have to wait for A's entire backlog. If the two
|
||||
@@ -979,7 +1019,7 @@ final class NostrRelayManagerTests: XCTestCase {
|
||||
)
|
||||
|
||||
// Both relays still drain fully and in order.
|
||||
let allDelivered = await waitUntil(timeout: 5.0) {
|
||||
let allDelivered = await waitUntil(timeout: TestConstants.settleTimeout) {
|
||||
busyDeliveredCount == busyEvents.count
|
||||
}
|
||||
XCTAssertTrue(allDelivered)
|
||||
@@ -1735,6 +1775,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 +1835,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 +1864,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(
|
||||
@@ -1811,7 +1907,7 @@ final class NostrRelayManagerTests: XCTestCase {
|
||||
}
|
||||
|
||||
private func waitUntil(
|
||||
timeout: TimeInterval = 1.0,
|
||||
timeout: TimeInterval = TestConstants.settleTimeout,
|
||||
condition: @escaping @MainActor () -> Bool
|
||||
) async -> Bool {
|
||||
let deadline = Date().addingTimeInterval(timeout)
|
||||
@@ -1845,6 +1941,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 {
|
||||
|
||||
@@ -164,7 +164,7 @@ struct NostrTransportTests {
|
||||
|
||||
transport.sendPrivateMessage("hello over nostr", to: shortPeerID, recipientNickname: "Carol", messageID: "pm-1")
|
||||
|
||||
let didSend = await TestHelpers.waitUntil({ probe.sentEvents.count == 1 }, timeout: 5.0)
|
||||
let didSend = await TestHelpers.waitUntil({ probe.sentEvents.count == 1 }, timeout: TestConstants.settleTimeout)
|
||||
#expect(didSend)
|
||||
let result = try decodeEmbeddedPayload(from: probe.sentEvents[0], recipient: recipient)
|
||||
let privateMessage = try decodePrivateMessage(from: result.payload)
|
||||
@@ -209,7 +209,7 @@ struct NostrTransportTests {
|
||||
|
||||
transport.sendFavoriteNotification(to: fullPeerID, isFavorite: true)
|
||||
|
||||
let didSend = await TestHelpers.waitUntil({ probe.sentEvents.count == 1 }, timeout: 5.0)
|
||||
let didSend = await TestHelpers.waitUntil({ probe.sentEvents.count == 1 }, timeout: TestConstants.settleTimeout)
|
||||
#expect(didSend)
|
||||
let result = try decodeEmbeddedPayload(from: probe.sentEvents[0], recipient: recipient)
|
||||
let privateMessage = try decodePrivateMessage(from: result.payload)
|
||||
@@ -250,7 +250,7 @@ struct NostrTransportTests {
|
||||
|
||||
transport.sendDeliveryAck(for: "ack-1", to: fullPeerID)
|
||||
|
||||
let didSend = await TestHelpers.waitUntil({ probe.sentEvents.count == 1 }, timeout: 5.0)
|
||||
let didSend = await TestHelpers.waitUntil({ probe.sentEvents.count == 1 }, timeout: TestConstants.settleTimeout)
|
||||
#expect(didSend)
|
||||
let result = try decodeEmbeddedPayload(from: probe.sentEvents[0], recipient: recipient)
|
||||
|
||||
@@ -288,7 +288,7 @@ struct NostrTransportTests {
|
||||
messageID: "geo-1"
|
||||
)
|
||||
|
||||
let didSend = await TestHelpers.waitUntil({ probe.sentEvents.count == 1 }, timeout: 5.0)
|
||||
let didSend = await TestHelpers.waitUntil({ probe.sentEvents.count == 1 }, timeout: TestConstants.settleTimeout)
|
||||
#expect(didSend)
|
||||
let event = probe.sentEvents[0]
|
||||
let result = try decodeEmbeddedPayload(from: event, recipient: recipient)
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
import BitFoundation
|
||||
import Foundation
|
||||
import Testing
|
||||
import UserNotifications
|
||||
@testable import bitchat
|
||||
|
||||
/// Lock-screen notifications used to carry the DM body and the sender's
|
||||
/// nickname verbatim, and the geohash in the title, so a locked phone lying on
|
||||
/// a table narrated conversations to anyone looking at it. These cover the
|
||||
/// redaction that is now the default.
|
||||
///
|
||||
/// The preference is injected rather than written to shared preferences. These
|
||||
/// run in the same process as `NotificationServiceTests`, and mutating the
|
||||
/// global store made whichever ran second depend on the other's cleanup — which
|
||||
/// passed locally and failed in CI.
|
||||
struct NotificationRedactionTests {
|
||||
private final class RecordingDeliverer: NotificationRequestDelivering {
|
||||
var requests: [UNNotificationRequest] = []
|
||||
|
||||
func add(_ request: UNNotificationRequest) {
|
||||
requests.append(request)
|
||||
}
|
||||
}
|
||||
|
||||
private struct StubAuthorizer: NotificationAuthorizing {
|
||||
func requestAuthorization(
|
||||
options: UNAuthorizationOptions,
|
||||
completionHandler: @escaping (Bool, Error?) -> Void
|
||||
) {
|
||||
completionHandler(true, nil)
|
||||
}
|
||||
}
|
||||
|
||||
private func makeService(
|
||||
hidePreviews: Bool
|
||||
) -> (NotificationService, RecordingDeliverer) {
|
||||
let deliverer = RecordingDeliverer()
|
||||
let service = NotificationService(
|
||||
isRunningTestsProvider: { false },
|
||||
authorizer: StubAuthorizer(),
|
||||
requestDeliverer: deliverer,
|
||||
hidePreviewsProvider: { hidePreviews }
|
||||
)
|
||||
return (service, deliverer)
|
||||
}
|
||||
|
||||
private func isolatedDefaults() -> UserDefaults {
|
||||
UserDefaults(suiteName: "bitchat.tests.notifications.\(UUID().uuidString)")!
|
||||
}
|
||||
|
||||
@Test func previewsAreHiddenByDefault() {
|
||||
// A fresh install must start quiet rather than opt-in quiet.
|
||||
#expect(NotificationPrivacySettings.hideMessagePreviews(in: isolatedDefaults()))
|
||||
}
|
||||
|
||||
@Test func theSettingRoundTrips() {
|
||||
let defaults = isolatedDefaults()
|
||||
|
||||
NotificationPrivacySettings.setHideMessagePreviews(false, in: defaults)
|
||||
#expect(!NotificationPrivacySettings.hideMessagePreviews(in: defaults))
|
||||
|
||||
// Panic wipe restores the safe default rather than the last choice.
|
||||
NotificationPrivacySettings.reset(in: defaults)
|
||||
#expect(NotificationPrivacySettings.hideMessagePreviews(in: defaults))
|
||||
}
|
||||
|
||||
@Test func redactedDirectMessageWithholdsSenderAndBody() throws {
|
||||
let (service, deliverer) = makeService(hidePreviews: true)
|
||||
|
||||
service.sendPrivateMessageNotification(
|
||||
from: "alice",
|
||||
message: "meet at the north gate",
|
||||
peerID: PeerID(str: "00112233445566ff")
|
||||
)
|
||||
|
||||
let content = try #require(deliverer.requests.first).content
|
||||
#expect(!content.title.contains("alice"))
|
||||
#expect(!content.body.contains("north gate"))
|
||||
#expect(!content.title.isEmpty)
|
||||
// Still routable: userInfo is never rendered on the lock screen.
|
||||
#expect(content.userInfo["peerID"] as? String == "00112233445566ff")
|
||||
}
|
||||
|
||||
@Test func redactedMentionWithholdsSenderAndBody() throws {
|
||||
let (service, deliverer) = makeService(hidePreviews: true)
|
||||
|
||||
service.sendMentionNotification(from: "bob", message: "regroup now")
|
||||
|
||||
let content = try #require(deliverer.requests.first).content
|
||||
#expect(!content.title.contains("bob"))
|
||||
#expect(!content.body.contains("regroup"))
|
||||
}
|
||||
|
||||
@Test func redactedGeohashActivityWithholdsTheGeohash() throws {
|
||||
let (service, deliverer) = makeService(hidePreviews: true)
|
||||
|
||||
service.sendGeohashActivityNotification(
|
||||
geohash: "u4pruyd",
|
||||
bodyPreview: "someone said something"
|
||||
)
|
||||
|
||||
let content = try #require(deliverer.requests.first).content
|
||||
#expect(!content.title.contains("u4pruyd"))
|
||||
#expect(!content.body.contains("someone said"))
|
||||
// The deep link still carries it: tapping must land in the channel.
|
||||
#expect(content.userInfo["deeplink"] as? String == "bitchat://geohash/u4pruyd")
|
||||
}
|
||||
|
||||
@Test func previewsShownWhenTheSettingIsOff() {
|
||||
let (service, deliverer) = makeService(hidePreviews: false)
|
||||
|
||||
service.sendPrivateMessageNotification(
|
||||
from: "alice",
|
||||
message: "meet at the north gate",
|
||||
peerID: PeerID(str: "00112233445566ff")
|
||||
)
|
||||
service.sendGeohashActivityNotification(
|
||||
geohash: "u4pruyd",
|
||||
bodyPreview: "someone said something"
|
||||
)
|
||||
|
||||
#expect(deliverer.requests.count == 2)
|
||||
let dm = deliverer.requests[0].content
|
||||
#expect(dm.title.contains("alice"))
|
||||
#expect(dm.body == "meet at the north gate")
|
||||
let geo = deliverer.requests[1].content
|
||||
#expect(geo.title.contains("u4pruyd"))
|
||||
#expect(geo.body == "someone said something")
|
||||
}
|
||||
}
|
||||
@@ -56,12 +56,15 @@ final class NotificationServiceTests: XCTestCase {
|
||||
XCTAssertNil(request?.trigger)
|
||||
}
|
||||
|
||||
/// Previews shown: the opt-in behavior. Stated explicitly rather than
|
||||
/// inherited from the shared preference, which now defaults to hidden.
|
||||
func test_sendPrivateMessageNotification_populatesPeerMetadata() {
|
||||
let deliverer = RecordingNotificationRequestDeliverer()
|
||||
let service = NotificationService(
|
||||
isRunningTestsProvider: { false },
|
||||
authorizer: RecordingNotificationAuthorizer(),
|
||||
requestDeliverer: deliverer
|
||||
requestDeliverer: deliverer,
|
||||
hidePreviewsProvider: { false }
|
||||
)
|
||||
let peerID = PeerID(str: "deadbeefdeadbeef")
|
||||
|
||||
@@ -74,6 +77,27 @@ final class NotificationServiceTests: XCTestCase {
|
||||
XCTAssertEqual(request?.content.userInfo["senderName"] as? String, "Alice")
|
||||
}
|
||||
|
||||
/// Previews hidden: the default. The routing payload has to survive
|
||||
/// redaction, or tapping the alert would not open the conversation.
|
||||
func test_sendPrivateMessageNotification_withPreviewsHidden_keepsRoutingButDropsContent() {
|
||||
let deliverer = RecordingNotificationRequestDeliverer()
|
||||
let service = NotificationService(
|
||||
isRunningTestsProvider: { false },
|
||||
authorizer: RecordingNotificationAuthorizer(),
|
||||
requestDeliverer: deliverer,
|
||||
hidePreviewsProvider: { true }
|
||||
)
|
||||
let peerID = PeerID(str: "deadbeefdeadbeef")
|
||||
|
||||
service.sendPrivateMessageNotification(from: "Alice", message: "hi", peerID: peerID)
|
||||
|
||||
let request = deliverer.requests.singleValue
|
||||
XCTAssertFalse(request?.content.title.contains("Alice") ?? true)
|
||||
XCTAssertFalse(request?.content.body.contains("hi") ?? true)
|
||||
XCTAssertFalse(request?.content.title.isEmpty ?? true)
|
||||
XCTAssertEqual(request?.content.userInfo["peerID"] as? String, peerID.id)
|
||||
}
|
||||
|
||||
func test_wrapperNotifications_setExpectedIdentifiersAndDeepLinks() {
|
||||
let deliverer = RecordingNotificationRequestDeliverer()
|
||||
let service = NotificationService(
|
||||
|
||||
@@ -562,7 +562,7 @@ final class SecureIdentityStateManagerTests: XCTestCase {
|
||||
}
|
||||
|
||||
private func waitUntil(
|
||||
timeout: TimeInterval = 1.0,
|
||||
timeout: TimeInterval = TestConstants.settleTimeout,
|
||||
condition: @escaping () -> Bool
|
||||
) async -> Bool {
|
||||
let deadline = Date().addingTimeInterval(timeout)
|
||||
|
||||
@@ -320,7 +320,7 @@ struct SecureIdentityStateManagerVouchTests {
|
||||
// MARK: - Helpers
|
||||
|
||||
private func waitUntil(
|
||||
timeout: TimeInterval = 1.0,
|
||||
timeout: TimeInterval = TestConstants.settleTimeout,
|
||||
condition: @escaping () -> Bool
|
||||
) async -> Bool {
|
||||
let deadline = Date().addingTimeInterval(timeout)
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
}
|
||||
@@ -48,7 +48,7 @@ struct GossipSyncBoardTests {
|
||||
let request = RequestSyncPacket(p: 4, m: 1, data: Data(), types: .board)
|
||||
manager.handleRequestSync(from: PeerID(str: "FFFFFFFFFFFFFFFF"), request: request)
|
||||
|
||||
try await TestHelpers.waitFor({ delegate.packets.count == 1 }, timeout: TestConstants.shortTimeout)
|
||||
try await TestHelpers.waitFor({ delegate.packets.count == 1 }, timeout: TestConstants.settleTimeout)
|
||||
let sent = try #require(delegate.packets.first)
|
||||
#expect(sent.type == MessageType.boardPost.rawValue)
|
||||
#expect(sent.isRSR)
|
||||
@@ -69,7 +69,7 @@ struct GossipSyncBoardTests {
|
||||
let boardRequest = RequestSyncPacket(p: 4, m: 1, data: Data(), types: .board)
|
||||
manager.handleRequestSync(from: PeerID(str: "FFFFFFFFFFFFFFFF"), request: boardRequest)
|
||||
|
||||
try await TestHelpers.waitFor({ delegate.packets.count == 1 }, timeout: TestConstants.shortTimeout)
|
||||
try await TestHelpers.waitFor({ delegate.packets.count == 1 }, timeout: TestConstants.settleTimeout)
|
||||
#expect(delegate.packets.count == 1)
|
||||
#expect(delegate.packets.first?.type == MessageType.boardPost.rawValue)
|
||||
}
|
||||
|
||||
@@ -63,7 +63,7 @@ final class RequestSyncManagerTests: XCTestCase {
|
||||
}
|
||||
|
||||
private func waitUntil(
|
||||
timeout: TimeInterval = 1.0,
|
||||
timeout: TimeInterval = TestConstants.settleTimeout,
|
||||
condition: @escaping () -> Bool
|
||||
) async -> Bool {
|
||||
let deadline = Date().addingTimeInterval(timeout)
|
||||
|
||||
@@ -11,14 +11,54 @@ import Foundation
|
||||
|
||||
struct TestConstants {
|
||||
static let defaultTimeout: TimeInterval = 5.0
|
||||
static let shortTimeout: TimeInterval = 1.0
|
||||
/// For positive waits on work that hops through `Task.detached` or
|
||||
/// background queues: those contend with every parallel test worker for
|
||||
/// the global executor, so a loaded CI runner can exceed
|
||||
/// `defaultTimeout`. `waitUntil` returns as soon as the condition holds,
|
||||
/// so passing runs never pay the longer timeout.
|
||||
static let longTimeout: TimeInterval = 10.0
|
||||
|
||||
|
||||
/// **Default deadline for any "wait until this async thing settles" helper.**
|
||||
///
|
||||
/// Four separate tests flaked on CI during July 2026 with the same root
|
||||
/// cause, and it is worth stating the rule rather than re-learning it a
|
||||
/// fifth time: *a wait deadline is not a latency budget.* It exists so a
|
||||
/// genuine hang eventually fails the suite. Size it for the worst-case
|
||||
/// scheduler, never for how long the operation "should" take.
|
||||
///
|
||||
/// A CI runner executes many suites at once. Work behind `@MainActor`,
|
||||
/// `Task.detached(priority: .utility)`, or a `DispatchQueue.asyncAfter` can
|
||||
/// be starved for seconds — one observed run took 3.75 s for a 1 s
|
||||
/// operation. Deadlines sized to the operation (the old 1 s defaults) turn
|
||||
/// that starvation into a red build that reads like a product bug.
|
||||
///
|
||||
/// This costs nothing when tests pass, because every helper returns as soon
|
||||
/// as its condition holds. It only extends the genuine-failure case.
|
||||
///
|
||||
/// `TestTimingHygieneTests` enforces that wait helpers default to at least
|
||||
/// `minimumSettleTimeout`.
|
||||
static let settleTimeout: TimeInterval = 30.0
|
||||
|
||||
/// Floor enforced by `TestTimingHygieneTests`. Anything below this is a
|
||||
/// latency assumption in disguise.
|
||||
static let minimumSettleTimeout: TimeInterval = 10.0
|
||||
|
||||
/// For waits whose **expected outcome is `false`** — "prove this does not
|
||||
/// happen".
|
||||
///
|
||||
/// The floor above is wrong for these, and inverted: a negative wait always
|
||||
/// runs its deadline out, so `settleTimeout` would spend 30 s per case
|
||||
/// proving nothing extra. Starvation cannot cause a false failure here
|
||||
/// either — a starved runner only makes the thing *less* likely to happen,
|
||||
/// so the assertion still holds. Short is correct, and naming it says the
|
||||
/// polarity out loud instead of leaving a bare literal that reads like the
|
||||
/// mistake this file exists to prevent.
|
||||
///
|
||||
/// `TestTimingHygieneTests` accepts this by name. Using it for a wait you
|
||||
/// expect to succeed reintroduces exactly the flake class it sits next to.
|
||||
static let negativeWaitWindow: TimeInterval = 1.0
|
||||
|
||||
|
||||
static let testNickname1 = "Alice"
|
||||
static let testNickname2 = "Bob"
|
||||
static let testNickname3 = "Charlie"
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
import Foundation
|
||||
import Testing
|
||||
|
||||
/// Guards the test suite against the flake class that produced four separate
|
||||
/// red builds in July 2026: **treating a wait deadline as a latency budget.**
|
||||
///
|
||||
/// A CI runner executes many suites at once, so work behind `@MainActor`,
|
||||
/// `Task.detached(priority: .utility)`, or `DispatchQueue.asyncAfter` can be
|
||||
/// starved for seconds. One observed run took 3.75 s for a 1 s operation.
|
||||
/// Deadlines sized to how long the operation "should" take turn that starvation
|
||||
/// into a red build that reads like a product bug, and the debugging cost lands
|
||||
/// on whoever opened an unrelated PR.
|
||||
///
|
||||
/// Two rules, both enforced below:
|
||||
///
|
||||
/// 1. A wait helper's default deadline must be at least
|
||||
/// `TestConstants.minimumSettleTimeout`. Waits return as soon as their
|
||||
/// condition holds, so a generous deadline is free in the passing case.
|
||||
/// 2. No test asserts an *upper bound* on elapsed wall-clock time. Such an
|
||||
/// assertion cannot distinguish the behaviour under test from a slow
|
||||
/// machine, so it can only be flaky. Assert the property somewhere it is
|
||||
/// computable — with an injected clock, on the pure logic — instead.
|
||||
///
|
||||
/// Both rules can be waived per line with `\(Self.waiver)` plus a reason, for
|
||||
/// the rare case where the timing itself is genuinely the thing under test.
|
||||
struct TestTimingHygieneTests {
|
||||
/// Opt-out marker. Reviewers should expect a reason next to it.
|
||||
static let waiver = "test-timing-ok:"
|
||||
|
||||
private static let testsRoot = URL(fileURLWithPath: #filePath)
|
||||
.deletingLastPathComponent() // TestUtilities
|
||||
.deletingLastPathComponent() // bitchatTests
|
||||
|
||||
private struct Line {
|
||||
let file: String
|
||||
let number: Int
|
||||
let text: String
|
||||
/// True when the waiver appears on this line or in the comment block
|
||||
/// immediately above it, so a reason can be written at readable length
|
||||
/// rather than crammed onto the end of the code line.
|
||||
let waived: Bool
|
||||
}
|
||||
|
||||
private static func swiftLines() throws -> [Line] {
|
||||
let enumerator = FileManager.default.enumerator(
|
||||
at: testsRoot,
|
||||
includingPropertiesForKeys: nil
|
||||
)
|
||||
var out: [Line] = []
|
||||
while let url = enumerator?.nextObject() as? URL {
|
||||
guard url.pathExtension == "swift" else { continue }
|
||||
// This file necessarily contains the patterns it bans.
|
||||
guard url.lastPathComponent != "TestTimingHygieneTests.swift" else { continue }
|
||||
let name = url.lastPathComponent
|
||||
let texts = try String(contentsOf: url, encoding: .utf8)
|
||||
.components(separatedBy: .newlines)
|
||||
for (index, text) in texts.enumerated() {
|
||||
// Scan back over an unbroken run of comment lines.
|
||||
var waived = text.contains(waiver)
|
||||
var back = index - 1
|
||||
while !waived, back >= 0 {
|
||||
let above = texts[back].trimmingCharacters(in: .whitespaces)
|
||||
guard above.hasPrefix("//") else { break }
|
||||
waived = above.contains(waiver)
|
||||
back -= 1
|
||||
}
|
||||
out.append(Line(file: name, number: index + 1, text: text, waived: waived))
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
private static func isWaived(_ line: Line) -> Bool {
|
||||
line.waived
|
||||
}
|
||||
|
||||
/// Rule 1: no wait helper may default to a deadline below the floor.
|
||||
@Test func waitHelpersDoNotDefaultToShortDeadlines() throws {
|
||||
let lines = try Self.swiftLines()
|
||||
#expect(!lines.isEmpty, "hygiene scan found no test sources — check the path")
|
||||
|
||||
// Two shapes, both of which have flaked here:
|
||||
// a declaration default — `timeout: TimeInterval = 2.5`
|
||||
// a wait call site — `wait(for:…, timeout: 1.0)`, `waitUntil(timeout: 5.0)`
|
||||
//
|
||||
// Deliberately NOT matched: a bare `timeout:` label on something that is
|
||||
// not a wait, such as the injected production handshake timeouts in the
|
||||
// Noise tests. Those are the behaviour under test, and a short value is
|
||||
// correct there.
|
||||
let patterns = [
|
||||
#"(?:timeout|deadline)\s*:\s*TimeInterval\s*=\s*([0-9]+(?:\.[0-9]+)?)"#,
|
||||
#"(?:wait|waitUntil|waitFor|fulfillment)\s*\([^)]*\btimeout:\s*([0-9]+(?:\.[0-9]+)?)"#
|
||||
].map { try? NSRegularExpression(pattern: $0) }.compactMap { $0 }
|
||||
#expect(patterns.count == 2, "hygiene regexes failed to compile")
|
||||
|
||||
// Named constants hide the same mistake behind a symbol, and did: the
|
||||
// fifth flake of the session was `timeout: TestConstants.shortTimeout`
|
||||
// (1 s) on a positive wait, which a literals-only scan cannot see.
|
||||
// `shortTimeout` itself is deleted (Periphery flagged it dead once its
|
||||
// last wait site converted); the ban stays so it cannot come back.
|
||||
// `negativeWaitWindow` is deliberately absent — short is correct there.
|
||||
let bannedConstants = ["shortTimeout", "defaultTimeout"]
|
||||
|
||||
var offenders: [String] = []
|
||||
for line in lines where !Self.isWaived(line) {
|
||||
let range = NSRange(line.text.startIndex..., in: line.text)
|
||||
var flagged = false
|
||||
for pattern in patterns {
|
||||
guard let match = pattern.firstMatch(in: line.text, range: range),
|
||||
let valueRange = Range(match.range(at: 1), in: line.text),
|
||||
let value = TimeInterval(line.text[valueRange]),
|
||||
value < TestConstants.minimumSettleTimeout else { continue }
|
||||
offenders.append("\(line.file):\(line.number) — \(value)s: \(line.text.trimmingCharacters(in: .whitespaces))")
|
||||
flagged = true
|
||||
break
|
||||
}
|
||||
guard !flagged else { continue }
|
||||
for name in bannedConstants
|
||||
where line.text.contains("timeout: TestConstants.\(name)") {
|
||||
offenders.append("\(line.file):\(line.number) — TestConstants.\(name): \(line.text.trimmingCharacters(in: .whitespaces))")
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
#expect(
|
||||
offenders.isEmpty,
|
||||
"""
|
||||
Wait deadlines below \(TestConstants.minimumSettleTimeout)s are latency \
|
||||
assumptions and will flake on a loaded runner. Use \
|
||||
TestConstants.settleTimeout, or add "\(Self.waiver) <reason>" if the \
|
||||
timing really is what the test asserts.
|
||||
|
||||
\(offenders.joined(separator: "\n"))
|
||||
"""
|
||||
)
|
||||
}
|
||||
|
||||
/// Rule 2: no test bounds elapsed wall-clock time from above.
|
||||
///
|
||||
/// This is the assertion that started it all — `XCTAssertLessThan(
|
||||
/// Date().timeIntervalSince(start), 1.4)` proving a debounce deadline was
|
||||
/// not restarted. It cannot separate "behaved correctly" from "runner was
|
||||
/// busy", so it only ever fails for the wrong reason.
|
||||
@Test func testsDoNotAssertUpperBoundsOnElapsedTime() throws {
|
||||
let lines = try Self.swiftLines()
|
||||
|
||||
let elapsedAssertion = try NSRegularExpression(
|
||||
pattern: #"(?:XCTAssertLessThan|XCTAssertLessThanOrEqual)\s*\(\s*(?:Date\(\)\.timeIntervalSince|[A-Za-z_][A-Za-z0-9_]*\.timeIntervalSince|ContinuousClock)"#
|
||||
)
|
||||
|
||||
var offenders: [String] = []
|
||||
for line in lines where !Self.isWaived(line) {
|
||||
let range = NSRange(line.text.startIndex..., in: line.text)
|
||||
guard elapsedAssertion.firstMatch(in: line.text, range: range) != nil else { continue }
|
||||
offenders.append("\(line.file):\(line.number) — \(line.text.trimmingCharacters(in: .whitespaces))")
|
||||
}
|
||||
|
||||
#expect(
|
||||
offenders.isEmpty,
|
||||
"""
|
||||
An upper bound on elapsed wall-clock time cannot distinguish the \
|
||||
behaviour under test from a slow machine. Assert the property where \
|
||||
it is computable — inject a clock, or test the pure logic — or add \
|
||||
"\(Self.waiver) <reason>".
|
||||
|
||||
\(offenders.joined(separator: "\n"))
|
||||
"""
|
||||
)
|
||||
}
|
||||
|
||||
/// The floor must stay meaningfully above the operations being waited on,
|
||||
/// and the default must satisfy the rule this file enforces.
|
||||
@Test func settleTimeoutsAreSelfConsistent() {
|
||||
#expect(TestConstants.settleTimeout >= TestConstants.minimumSettleTimeout)
|
||||
#expect(TestConstants.minimumSettleTimeout > TestConstants.defaultTimeout)
|
||||
}
|
||||
}
|
||||
@@ -554,6 +554,103 @@ struct ViewSmokeTests {
|
||||
#expect(featureModels.privateConversationModel.selectedHeaderState?.headerPeerID == peerID)
|
||||
}
|
||||
|
||||
@Test("Root Bluetooth alert waits for location and notices sheets")
|
||||
func rootBluetoothAlertGuard_includesHeaderSheets() {
|
||||
#expect(!ContentRootModalPresentationState().hasPresentation)
|
||||
#expect(
|
||||
ContentRootModalPresentationState(
|
||||
isLocationChannelsSheetPresented: true
|
||||
).hasPresentation
|
||||
)
|
||||
#expect(
|
||||
ContentRootModalPresentationState(
|
||||
isNoticesSheetPresented: true
|
||||
).hasPresentation
|
||||
)
|
||||
}
|
||||
|
||||
@Test("People-sheet Bluetooth alert waits for local verification sheet")
|
||||
func peopleSheetBluetoothAlertGuard_includesVerificationSheet() {
|
||||
#expect(!ContentPeopleSheetModalPresentationState().hasPresentation)
|
||||
#expect(
|
||||
ContentPeopleSheetModalPresentationState(
|
||||
isVerificationSheetPresented: true
|
||||
).hasPresentation
|
||||
)
|
||||
}
|
||||
|
||||
@Test("Bluetooth alerts wait for the voice recording error alert")
|
||||
func bluetoothAlertGuards_includeVoiceAlert() {
|
||||
#expect(
|
||||
ContentRootModalPresentationState(
|
||||
isVoiceAlertPresented: true
|
||||
).hasPresentation
|
||||
)
|
||||
#expect(
|
||||
ContentPeopleSheetModalPresentationState(
|
||||
isVoiceAlertPresented: true
|
||||
).hasPresentation
|
||||
)
|
||||
}
|
||||
|
||||
@Test("Root Bluetooth alert waits for screenshot privacy alert")
|
||||
@MainActor
|
||||
func rootBluetoothAlertGuard_tracksScreenshotPrivacyState() {
|
||||
let (viewModel, _, _) = makeSmokeViewModel()
|
||||
let featureModels = makeSmokeFeatureModels(for: viewModel)
|
||||
|
||||
#expect(
|
||||
!ContentRootModalPresentationState(
|
||||
appChromeModel: featureModels.appChromeModel
|
||||
).hasPresentation
|
||||
)
|
||||
|
||||
featureModels.appChromeModel.showScreenshotPrivacyWarning = true
|
||||
|
||||
#expect(
|
||||
ContentRootModalPresentationState(
|
||||
appChromeModel: featureModels.appChromeModel
|
||||
).hasPresentation
|
||||
)
|
||||
}
|
||||
|
||||
@Test("People-sheet Bluetooth alert waits for legacy media consent")
|
||||
@MainActor
|
||||
func peopleSheetBluetoothAlertGuard_tracksLegacyConsentState() async {
|
||||
let (viewModel, _, _) = makeSmokeViewModel()
|
||||
let featureModels = makeSmokeFeatureModels(for: viewModel)
|
||||
|
||||
#expect(
|
||||
!ContentPeopleSheetModalPresentationState(
|
||||
legacyPrivateMediaConsentRequest:
|
||||
featureModels.conversationUIModel
|
||||
.legacyPrivateMediaConsentRequest
|
||||
).hasPresentation
|
||||
)
|
||||
|
||||
viewModel.enqueueLegacyPrivateMediaConsent(
|
||||
for: PeerID(str: "5152535455565758"),
|
||||
transferId: "legacy-consent-transfer",
|
||||
messageID: "legacy-consent-message"
|
||||
) { _ in }
|
||||
defer { viewModel.cancelAllLegacyPrivateMediaConsents() }
|
||||
|
||||
let consentPropagated = await TestHelpers.waitUntil {
|
||||
featureModels.conversationUIModel
|
||||
.legacyPrivateMediaConsentRequest != nil
|
||||
}
|
||||
#expect(
|
||||
consentPropagated
|
||||
)
|
||||
#expect(
|
||||
ContentPeopleSheetModalPresentationState(
|
||||
legacyPrivateMediaConsentRequest:
|
||||
featureModels.conversationUIModel
|
||||
.legacyPrivateMediaConsentRequest
|
||||
).hasPresentation
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
func geohashAndTextMessageViews_renderCoreBranches() {
|
||||
let (viewModel, _, _) = makeSmokeViewModel()
|
||||
|
||||
@@ -101,7 +101,7 @@ struct VoiceCaptureSessionTests {
|
||||
_ condition: () -> Bool,
|
||||
sourceLocation: SourceLocation = #_sourceLocation
|
||||
) async {
|
||||
let deadline = ContinuousClock.now.advanced(by: .seconds(5))
|
||||
let deadline = ContinuousClock.now.advanced(by: .seconds(TestConstants.settleTimeout))
|
||||
while !condition(), ContinuousClock.now < deadline {
|
||||
await Task.yield()
|
||||
try? await Task.sleep(nanoseconds: 1_000_000)
|
||||
|
||||
@@ -59,11 +59,24 @@ struct VoiceNotePlaybackControllerTests {
|
||||
return url
|
||||
}
|
||||
|
||||
/// Waits for an async settle, then asserts.
|
||||
///
|
||||
/// The deadline is deliberately far larger than the work it waits on. Every
|
||||
/// condition here depends on a `@MainActor` Task that playback schedules
|
||||
/// (the session acquire and its failure path), and on a CI runner executing
|
||||
/// many suites in parallel that Task can simply not be scheduled for
|
||||
/// seconds. At five seconds this timed out on CI and reported *two*
|
||||
/// failures — the wait itself, and the `!isPlaying` that the un-run failure
|
||||
/// path had not yet reset — which reads like a playback bug rather than a
|
||||
/// starved scheduler.
|
||||
///
|
||||
/// A generous deadline costs nothing when the condition holds, since this
|
||||
/// returns as soon as it does; it only extends the genuine-failure case.
|
||||
private func waitUntil(
|
||||
_ condition: () -> Bool,
|
||||
sourceLocation: SourceLocation = #_sourceLocation
|
||||
) async {
|
||||
let deadline = ContinuousClock.now.advanced(by: .seconds(5))
|
||||
let deadline = ContinuousClock.now.advanced(by: .seconds(TestConstants.settleTimeout))
|
||||
while !condition(), ContinuousClock.now < deadline {
|
||||
await Task.yield()
|
||||
try? await Task.sleep(nanoseconds: 1_000_000)
|
||||
|
||||
@@ -13,17 +13,16 @@ import Testing
|
||||
private final class VoiceRecorderTestSession: SessionApplying, @unchecked Sendable {
|
||||
private let lock = NSLock()
|
||||
private let activationGate = DispatchSemaphore(value: 0)
|
||||
private let activationBeganGate = DispatchSemaphore(value: 0)
|
||||
private let shouldGateFirstActivation: Bool
|
||||
private var gatedFirstActivation = false
|
||||
private var _activationCalls: [Bool] = []
|
||||
private var _activationBegan = false
|
||||
|
||||
init(gateFirstActivation: Bool = false) {
|
||||
self.shouldGateFirstActivation = gateFirstActivation
|
||||
}
|
||||
|
||||
var activationCalls: [Bool] { lock.withLock { _activationCalls } }
|
||||
var activationBegan: Bool { lock.withLock { _activationBegan } }
|
||||
|
||||
func setCategory(_ category: AudioSessionCoordinator.Category) throws {}
|
||||
|
||||
@@ -32,14 +31,28 @@ private final class VoiceRecorderTestSession: SessionApplying, @unchecked Sendab
|
||||
_activationCalls.append(active)
|
||||
guard active, shouldGateFirstActivation, !gatedFirstActivation else { return false }
|
||||
gatedFirstActivation = true
|
||||
_activationBegan = true
|
||||
return true
|
||||
}
|
||||
if shouldWait {
|
||||
activationBeganGate.signal()
|
||||
activationGate.wait()
|
||||
}
|
||||
}
|
||||
|
||||
func waitUntilActivationBegan(
|
||||
timeout: DispatchTimeInterval = .seconds(5)
|
||||
) async -> Bool {
|
||||
await withCheckedContinuation { continuation in
|
||||
DispatchQueue.global(qos: .userInitiated).async {
|
||||
continuation.resume(
|
||||
returning: self.activationBeganGate.wait(
|
||||
timeout: DispatchTime.now() + timeout
|
||||
) == .success
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func resumeActivation() {
|
||||
activationGate.signal()
|
||||
}
|
||||
@@ -142,26 +155,38 @@ private final class TestVoiceAudioRecorderFactory: VoiceAudioRecorderCreating {
|
||||
/// this remains deterministic when the full test suite saturates the executor.
|
||||
private final class VoiceRecorderPaddingGate: @unchecked Sendable {
|
||||
private let lock = NSLock()
|
||||
private var _entered = false
|
||||
private let enteredGate = DispatchSemaphore(value: 0)
|
||||
private var isOpen = false
|
||||
private var openWaiters: [CheckedContinuation<Void, Never>] = []
|
||||
|
||||
var entered: Bool { lock.withLock { _entered } }
|
||||
|
||||
func wait() async {
|
||||
await withCheckedContinuation { continuation in
|
||||
let resumeImmediately = lock.withLock { () -> Bool in
|
||||
_entered = true
|
||||
guard !isOpen else { return true }
|
||||
openWaiters.append(continuation)
|
||||
return false
|
||||
}
|
||||
enteredGate.signal()
|
||||
if resumeImmediately {
|
||||
continuation.resume()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func waitUntilEntered(
|
||||
timeout: DispatchTimeInterval = .seconds(5)
|
||||
) async -> Bool {
|
||||
await withCheckedContinuation { continuation in
|
||||
DispatchQueue.global(qos: .userInitiated).async {
|
||||
continuation.resume(
|
||||
returning: self.enteredGate.wait(
|
||||
timeout: DispatchTime.now() + timeout
|
||||
) == .success
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func open() {
|
||||
let waiters = lock.withLock { () -> [CheckedContinuation<Void, Never>] in
|
||||
isOpen = true
|
||||
@@ -181,18 +206,6 @@ struct VoiceRecorderTests {
|
||||
return url
|
||||
}
|
||||
|
||||
private func waitUntil(
|
||||
_ condition: () -> Bool,
|
||||
sourceLocation: SourceLocation = #_sourceLocation
|
||||
) async {
|
||||
let deadline = ContinuousClock.now.advanced(by: .seconds(5))
|
||||
while !condition(), ContinuousClock.now < deadline {
|
||||
await Task.yield()
|
||||
try? await Task.sleep(nanoseconds: 1_000_000)
|
||||
}
|
||||
#expect(condition(), sourceLocation: sourceLocation)
|
||||
}
|
||||
|
||||
@Test func cancelWhileSessionAcquireIsInFlightNeverCreatesARecorder() async throws {
|
||||
let directory = try makeTemporaryDirectory()
|
||||
defer { try? FileManager.default.removeItem(at: directory) }
|
||||
@@ -210,7 +223,7 @@ struct VoiceRecorderTests {
|
||||
let owner = VoiceRecorder.RecordingOwner()
|
||||
|
||||
let startTask = Task { try await voiceRecorder.startRecording(owner: owner) }
|
||||
await waitUntil { session.activationBegan }
|
||||
#expect(await session.waitUntilActivationBegan())
|
||||
|
||||
await voiceRecorder.cancelRecording(owner: owner)
|
||||
session.resumeActivation()
|
||||
@@ -308,7 +321,7 @@ struct VoiceRecorderTests {
|
||||
try await finishingHold.start()
|
||||
let firstURL = try #require(factory.urls.first)
|
||||
let finishTask = Task { await finishingHold.finish() }
|
||||
await waitUntil { paddingGate.entered }
|
||||
#expect(await paddingGate.waitUntilEntered())
|
||||
|
||||
await #expect(throws: VoiceRecorder.RecorderError.recordingInProgress) {
|
||||
try await rejectedHold.start()
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
# BLE Transport Architecture V3
|
||||
|
||||
The plan of record for restructuring `BLEService` from an 8.3k-line god
|
||||
object into a layered mesh stack. ARCHITECTURE_V2 rebuilt the app layer
|
||||
above the transport and deliberately deferred the transport itself; this
|
||||
document covers that remainder: what already landed, the target shape, and
|
||||
the order for the rest.
|
||||
|
||||
## Why the satellite strategy stalled
|
||||
|
||||
V2's transport approach was to peel pure policies and closure-driven
|
||||
handlers out of `BLEService` while the class kept coordinating. The ~30
|
||||
pure policy structs were a clear win. The five big handler extractions
|
||||
were not: each needed an "environment" of 20–30 closures that weakly
|
||||
capture the service and hop queues back into its state. Logic left, but
|
||||
state ownership and synchronization never moved, so extraction paid a
|
||||
plumbing tax that grew as fast as the logic shrank — the five
|
||||
`make*HandlerEnvironment()` factories alone were ~1.5k lines. The file
|
||||
held ~60 mutable fields across four concurrency domains whose ownership
|
||||
lived in comments, and every new feature added Transport requirements,
|
||||
state maps, and switch cases to the same class.
|
||||
|
||||
Two chronic costs came straight from that structure: queue-order
|
||||
deadlocks (the July 9 main↔bleQueue ABBA freeze), and timing-dependent
|
||||
tests (correctness only observable through real queues and real time).
|
||||
|
||||
## Target shape
|
||||
|
||||
A packet-radio stack with one rule per layer about state and threads:
|
||||
|
||||
1. **`BLELinkLayer`** — the only CoreBluetooth import. Owns both managers,
|
||||
scanning/advertising, duty cycle, connection scheduling, MTU, write
|
||||
and notification backpressure buffers, state restoration. Speaks
|
||||
`LinkEvent` up (link up/down, bytes in, writable) and `LinkCommand`
|
||||
down (send bytes on link, scan/advertise policy). Knows nothing about
|
||||
packets, peers, or Noise. bleQueue-confined. A `SimulatedLinkLayer`
|
||||
implementing the same port gives multi-node tests real topologies with
|
||||
no radios and no wall-clock waits.
|
||||
2. **Mesh engine** — one serial queue owning all protocol state: wire
|
||||
codec, fragmentation, dedup, relay policy, peer registry, topology,
|
||||
gossip sync, Noise orchestration. Synchronous single-writer logic; the
|
||||
pure policy satellites slot in unchanged. Endgame: the engine core
|
||||
becomes `handle(event, now) -> [Effect]` (sans-I/O), which makes the
|
||||
whole mesh property-testable and fuzzable in simulation.
|
||||
3. **Feature modules** — courier, board, prekeys, private media, file
|
||||
transfer, voice, diagnostics, groups, verify/vouch each own their
|
||||
state and register for their message types. A new feature is a new
|
||||
module, not edits to the engine.
|
||||
4. **App boundary** — a small `Transport` core both transports genuinely
|
||||
implement, plus capability protocols discovered with `as?`
|
||||
(`MeshBridgingTransport` etc.), replacing the ~90-requirement
|
||||
god-protocol and its inert defaults.
|
||||
|
||||
### Concurrency contract
|
||||
|
||||
State is owned one of three ways:
|
||||
|
||||
- **Engine-confined** — mutated only on the serial engine queue
|
||||
(`mesh.message`). Cross-thread callers use `onEngine`.
|
||||
- **bleQueue-confined** — link-layer state next to CoreBluetooth objects
|
||||
(link store, write/notification buffers, link-auth maps).
|
||||
- **Lock-backed store** — state with legitimate cross-domain readers
|
||||
(peer registry, local identity/capabilities, traffic monitor). Writes
|
||||
still come from one domain; the lock exists so readers never block on
|
||||
a queue. Every mutation is a single whole-transition method, so
|
||||
readers never observe torn state.
|
||||
|
||||
Sync-edge order (deadlock freedom by construction, debug-enforced in
|
||||
`onEngine`):
|
||||
|
||||
```
|
||||
main / test threads ──sync──▶ engine ──sync──▶ bleQueue
|
||||
└──sync──▶ noise / identity queues (leaves)
|
||||
```
|
||||
|
||||
Nothing may sync-wait in the reverse direction: bleQueue and the crypto
|
||||
queues reach the engine only via `async`, and nothing sync-dispatches to
|
||||
main. Two subtleties worth knowing:
|
||||
|
||||
- A closure executed inside a noise-manager critical section entered
|
||||
*from* an engine slot may touch engine state directly (the blocked
|
||||
slot makes it exclusive) but must never sync-re-enter the engine —
|
||||
that is a self-deadlock.
|
||||
- bleQueue critical sections (e.g. the verified-announce link rebind)
|
||||
must receive engine-derived values as arguments rather than fetching
|
||||
them through `onEngine`.
|
||||
|
||||
## What landed in this pass
|
||||
|
||||
- **Lock-backed peer state** (`BLEPeerRegistryStore`): every main-actor
|
||||
Transport read (`isPeerConnected`, nicknames, snapshots, capability
|
||||
queries) reads a lock, not a queue. Runtime capability bits moved into
|
||||
`BLELocalIdentityStateStore` beside the identity they ride announces
|
||||
with.
|
||||
- **bleQueue owns the link buffers**: `pendingPeripheralWrites`,
|
||||
`pendingNotifications`, `pendingWriteBuffers` are bleQueue-confined
|
||||
(their producers and drains already ran there); the notification drain
|
||||
no longer invokes CoreBluetooth from a transport queue.
|
||||
- **One serial engine queue**: the concurrent message queue and the
|
||||
collections queue it guarded state with are one serial domain; every
|
||||
barrier flag and per-field ownership comment deleted; ~98 cross-queue
|
||||
hops removed. `onEngine` documents and debug-enforces the sync-edge
|
||||
order — and its trap caught two latent inversions during migration
|
||||
(the announce-rebind path and the noise session-generation closures).
|
||||
- **Capability ports**: gateway/bridge/courier wiring, the panic
|
||||
lifecycle, and radio-state reads go through `MeshBridgingTransport`,
|
||||
`PanicResettingTransport`, and `BluetoothStateReporting`; no app code
|
||||
casts to `BLEService` anymore.
|
||||
- **First feature-owned state**: `BLEMeshPingTracker` holds the /ping
|
||||
probe map and per-link response budget as pure state with unit tests —
|
||||
the template for peeling the remaining features.
|
||||
|
||||
Full suite green throughout (1,953 tests), identical wall-clock — BLE
|
||||
throughput is nowhere near what one serial queue sustains.
|
||||
|
||||
## Remaining roadmap (in order)
|
||||
|
||||
1. **Feature peeling.** Move each feature's state maps and handlers into
|
||||
a module in the `BLEMeshPingTracker` mold: private media (six
|
||||
generation-keyed maps + policy resolution — its main-actor reads
|
||||
become a lock-backed store inside the module), courier, prekeys,
|
||||
board, voice, file transfer, groups. The engine keeps a registry of
|
||||
handled message types instead of a giant switch. Each module lands as
|
||||
its own PR with its state's invariants unit-tested.
|
||||
2. **Transport protocol split.** Continue what the capability ports
|
||||
started: `Transport` shrinks to lifecycle + identity + snapshots +
|
||||
basic messaging; files/voice/courier/board/diagnostics/verification
|
||||
become capability protocols; `NostrTransport` drops its inert stubs;
|
||||
coordinators declare the capability they need instead of receiving
|
||||
the whole god-protocol (~48 call sites across 14 files).
|
||||
3. **Link-layer extraction.** With the file slimmed, move the CB
|
||||
delegates, scheduling, duty cycle, and buffers behind
|
||||
`LinkEvent`/`LinkCommand` ports. Decide the link-auth boundary here:
|
||||
`noiseAuthenticatedLinkOwners` and the rebind containment rules are
|
||||
mesh security state that currently lives on bleQueue for atomicity
|
||||
with bindings — the port design must keep "binding + auth check" one
|
||||
critical section or make bindings engine-owned.
|
||||
4. **Sans-I/O engine core + simulator.** Make the engine formally
|
||||
`handle(event) -> [Effect]`, feed it from a `SimulatedLinkLayer`, and
|
||||
move the multi-node E2E suite onto deterministic simulation (no
|
||||
`waitUntil`, no timing hygiene battles). Property tests become
|
||||
possible: relay-storm bounds, partition-heal convergence, dedup
|
||||
soundness under duplicate floods.
|
||||
|
||||
## What this is not
|
||||
|
||||
No wire changes: packet formats, signing (padding is signed), the
|
||||
peerID identity binding, and courier tag construction are untouched —
|
||||
see the wire-landmines notes before assuming any of that is local.
|
||||
+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,94 @@
|
||||
# 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.
|
||||
|
||||
Keep the downloaded manifest *outside* the source tree (say, `/tmp`) — a stray copy inside the checkout would itself trip the completeness checks below. Then check a copy of the source against it:
|
||||
|
||||
```sh
|
||||
# From the root of the source you obtained, with the manifest at /tmp
|
||||
grep -v '^#' /tmp/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.
|
||||
|
||||
That check alone is not enough. `shasum -c` verifies the files the manifest lists and says nothing about files it does not list — and the Xcode project compiles every source file present in the tree automatically, so a hostile mirror can pass the hash check by leaving every listed file intact and *adding* one. Confirm nothing extra is present:
|
||||
|
||||
```sh
|
||||
# The manifest's path list must match the tree exactly — no missing files, no extras
|
||||
grep -v '^#' /tmp/SOURCE-MANIFEST.txt | sed 's/^[0-9a-f]* //' | LC_ALL=C sort > /tmp/manifest-paths
|
||||
find . -type f ! -path './.git/*' | sed 's|^\./||' | LC_ALL=C sort > /tmp/actual-paths
|
||||
diff /tmp/manifest-paths /tmp/actual-paths # must print nothing
|
||||
```
|
||||
|
||||
In a git checkout the same assurance is one command — it also catches extra files, because they show as untracked. `--ignored` matters: `.gitignore` covers paths like `build/`, plain `git status` would not report a planted file there, and Xcode compiles it all the same:
|
||||
|
||||
```sh
|
||||
git status --porcelain --ignored # must print nothing before you build
|
||||
```
|
||||
|
||||
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
|
||||
```
|
||||
|
||||
Note the tree hash covers tracked content only; it does not see untracked files sitting in the working directory, which is why the emptiness checks above come first.
|
||||
|
||||
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 /tmp/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.
|
||||
@@ -18,6 +18,7 @@ The user-facing contract is `PRIVACY_POLICY.md`. This document records implement
|
||||
- Private payloads are end-to-end encrypted, but public mesh, board, bridge, and geohash content is intentionally visible to its participants.
|
||||
- Local storage is bounded where practical and included in panic wipe, but it is not wholly ephemeral. The app persists the stores listed below.
|
||||
- The app and share extension each bundle a privacy manifest declaring their actual required-reason API use.
|
||||
- A locked device discloses less than an unlocked one, but not nothing. Notification previews are hidden by default and the app-switcher snapshot is covered; see "Locked and Seized Devices".
|
||||
|
||||
## BLE Discovery and Metadata
|
||||
|
||||
@@ -28,7 +29,9 @@ Signed announces can expose:
|
||||
- A bounded set of short direct-neighbor identifiers
|
||||
- A coarse rendezvous geohash when the bridge capability is enabled
|
||||
|
||||
The app does not advertise the device's user-assigned name. iOS manages BLE address randomization; bitchat does not attempt to create a stable MAC address. RSSI, timing, traffic volume, and radio fingerprints remain observable to nearby receivers.
|
||||
The app does not advertise the device's assigned name. iOS manages BLE address randomization; bitchat does not attempt to create a stable MAC address.
|
||||
|
||||
That randomization does not deliver the unlinkability it might suggest, because the application layer publishes stable identifiers above it. The 8-byte peer ID in every packet header is the first 8 bytes of the Noise static key fingerprint, so it does not rotate; announces carry the static keys themselves; and the fixed service UUID makes any bitchat device detectable as such by a passive scanner. A receiver in radio range can therefore recognise a specific device across sessions and locations, and detect that the app is in use at all. RSSI, timing, traffic volume, and radio fingerprints remain observable as well.
|
||||
|
||||
Ingress validates announce structure, sender binding, signatures, payload sizes, and freshness. Current-link Noise authentication is required before destructive courier handoff or strict directed delivery. Floods, queues, fragments, ingress work, and per-peer state are bounded.
|
||||
|
||||
@@ -45,10 +48,10 @@ Residual risk: private-message metadata such as timing, radio adjacency, ciphert
|
||||
|
||||
## Public Gossip, Boards, and Media
|
||||
|
||||
- Recent signed public mesh messages are archived in Application Support for up to 15 minutes so gossip sync survives a relaunch and can cross mesh partitions.
|
||||
- Recent signed public mesh messages are archived in Application Support for up to 6 hours so gossip sync survives a relaunch and can cross mesh partitions.
|
||||
- Signed public board posts and tombstones persist until author-selected expiry, at most seven days. Stores are bounded by global and per-author quotas.
|
||||
- Group metadata (name, roster, creator, epoch) persists as protected JSON; group keys live in the keychain until leave/removal/wipe.
|
||||
- Voice notes and images are stored in Application Support. Incoming media has a 100 MB oldest-first quota; outgoing media does not have an equivalent automatic lifetime and remains until cleanup, panic wipe, or app removal. Panic wipe invalidates detached preparation work, cancels active transfers, closes live capture files, and removes the managed media tree before returning.
|
||||
- Voice notes and images are stored in Application Support. Incoming media has a 100 MB oldest-first quota, and all managed media — incoming and outgoing — is additionally bounded by age: a launch-time sweep deletes anything older than seven days. In-flight live captures and files reserved by a delivery or deletion in progress are exempt regardless of age. Panic wipe invalidates detached preparation work, cancels active transfers, closes live capture files, and removes the managed media tree before returning.
|
||||
|
||||
Public archives contain content already intended for public mesh/board distribution, but a seized unlocked device can reveal it. Group metadata and media can reveal relationships or content even when the in-memory chat timeline has gone away.
|
||||
|
||||
@@ -60,6 +63,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
|
||||
@@ -86,9 +92,24 @@ Residual risk: Nostr relay retention and logging are outside project control. Pu
|
||||
|
||||
`bitchatShareExtension/PrivacyInfo.xcprivacy` declares app-group UserDefaults reason `1C8F.1`. Both manifests declare no tracking domains and no data collection by the app developer. They must remain bundled in their respective executable bundles.
|
||||
|
||||
## Locked and Seized Devices
|
||||
|
||||
The realistic compromise for many of the people this app is built for is not interception but a phone taken and, often, unlocked under coercion.
|
||||
|
||||
- Notification content is rendered by the system on the lock screen, so it is readable without unlocking. Message previews are therefore hidden by default: alerts state that a direct message, mention, or location-channel activity arrived, and withhold the message body, the sender's nickname, and the geohash until the app is opened. `userInfo` still carries the routing peer ID and deep link, neither of which the system displays. The preference is `notifications.hideMessagePreviews`; turning it off restores full previews.
|
||||
- The window is covered on `willResignActive`, so the snapshot iOS stores for the app switcher shows a placeholder rather than an open conversation. The cover is opaque rather than blurred, and is added synchronously because the capture follows shortly after that notification. Panic wipe separately deletes snapshots already on disk.
|
||||
- Clearing a mesh timeline erases the on-disk gossip archive behind it, so cleared public history is deleted rather than hidden. The echo watermark still suppresses pre-clear messages this device hears again from peers.
|
||||
- Managed media is bounded by age as well as size, so a received photo does not outlive its conversation indefinitely.
|
||||
|
||||
Not addressed, and deliberately out of scope here:
|
||||
|
||||
- **No duress mechanism.** There is no decoy passphrase, no wipe-on-failed-authentication, and no biometric or passcode lock on the app itself. A coerced unlock discloses everything the device still holds. Adding one is a product decision as much as an engineering one: in some jurisdictions destroying data on demand is itself an offence, so a mode that *hides* may protect someone better than one that *destroys*, and the choice should be made deliberately rather than by default.
|
||||
- **macOS gets no file-protection classes.** Every `FileProtectionType` application is inside `#if os(iOS)`; Data Protection on macOS additionally requires an entitlement. The Mac app also has no app-switcher equivalent.
|
||||
- **Media is not sealed at the app layer.** It relies on the platform default protection class, which is readable once the device has been unlocked since boot. Sealing under a key with the same accessibility would not change that; only a key gated on user authentication would, and that conflicts with receiving media while locked.
|
||||
|
||||
## 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
|
||||
|
||||
@@ -97,3 +118,4 @@ The panic action clears identity/session state, preferences, location state, gro
|
||||
- Verify panic wipe reaches any newly added persistent store.
|
||||
- Treat geohash precision, bridge-cell changes, new relay tags, and announce fields as privacy-surface changes.
|
||||
- Re-run real-device Bluetooth, background/locked-device recovery, location revocation, and audio-route checks; simulators cannot validate the physical side of those behaviors.
|
||||
- Check what a new notification discloses on a locked screen, and that the app-switcher snapshot is covered, whenever notification or scene-lifecycle code changes.
|
||||
|
||||
@@ -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() } }
|
||||
@@ -75,6 +84,10 @@ public final class TorManager: ObservableObject {
|
||||
private var shutdownsInFlight = 0
|
||||
private var startPendingAfterShutdown = false
|
||||
private var bootstrapMonitorStarted = false
|
||||
// Fences the detached poll loop: shutdown, dormancy, and restart each bump
|
||||
// this, so a loop from a previous attempt cannot run out its deadline and
|
||||
// report a stall over state that a newer lifecycle event already owns.
|
||||
private var bootstrapGeneration = 0
|
||||
private var pathMonitor: NWPathMonitor?
|
||||
private var isAppForeground: Bool = true
|
||||
private var lastRestartAt: Date? = nil
|
||||
@@ -96,6 +109,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
|
||||
@@ -258,27 +272,47 @@ public final class TorManager: ObservableObject {
|
||||
private func startBootstrapMonitor() {
|
||||
guard !bootstrapMonitorStarted else { return }
|
||||
bootstrapMonitorStarted = true
|
||||
bootstrapGeneration += 1
|
||||
let generation = bootstrapGeneration
|
||||
Task.detached(priority: .utility) { [weak self] in
|
||||
await self?.bootstrapPollLoop()
|
||||
await self?.bootstrapPollLoop(generation: generation)
|
||||
}
|
||||
}
|
||||
|
||||
private func bootstrapPollLoop() async {
|
||||
private func bootstrapPollLoop(generation: Int) async {
|
||||
let deadline = Date().addingTimeInterval(75)
|
||||
var didComplete = false
|
||||
while Date() < deadline {
|
||||
guard generation == bootstrapGeneration else { return }
|
||||
let progress = Int(arti_bootstrap_progress())
|
||||
let summary = getBootstrapSummary()
|
||||
|
||||
await MainActor.run {
|
||||
self.bootstrapProgress = progress
|
||||
self.bootstrapSummary = summary
|
||||
if progress >= 100 { self.isStarting = false }
|
||||
self.recomputeReady()
|
||||
}
|
||||
self.bootstrapProgress = progress
|
||||
self.bootstrapSummary = summary
|
||||
if progress >= 100 { self.isStarting = false }
|
||||
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. A deliberate
|
||||
// shutdown mid-bootstrap is not a stall, hence the generation check.
|
||||
if !didComplete {
|
||||
guard generation == bootstrapGeneration else { return }
|
||||
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 {
|
||||
@@ -323,6 +357,7 @@ public final class TorManager: ObservableObject {
|
||||
// Clear isStarting so foreground recovery can proceed if bootstrap was interrupted.
|
||||
SecureLogger.debug("TorManager: goDormantOnBackground() called", category: .session)
|
||||
Task { @MainActor in
|
||||
self.bootstrapGeneration += 1
|
||||
self.isReady = false
|
||||
self.socksReady = false
|
||||
self.isStarting = false
|
||||
@@ -332,6 +367,7 @@ public final class TorManager: ObservableObject {
|
||||
public func shutdownCompletely() {
|
||||
SecureLogger.debug("TorManager: shutdownCompletely() called", category: .session)
|
||||
startPendingAfterShutdown = false
|
||||
bootstrapGeneration += 1
|
||||
shutdownsInFlight += 1
|
||||
Task.detached { [weak self] in
|
||||
guard let self = self else { return }
|
||||
@@ -369,11 +405,13 @@ public final class TorManager: ObservableObject {
|
||||
SecureLogger.debug("TorManager: restartArti() starting", category: .session)
|
||||
await MainActor.run {
|
||||
NotificationCenter.default.post(name: .TorWillRestart, object: nil)
|
||||
self.bootstrapGeneration += 1
|
||||
self.isReady = false
|
||||
self.socksReady = false
|
||||
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")
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user