mirror of
https://github.com/permissionlesstech/bitchat.git
synced 2026-07-27 09:25:20 +00:00
Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2ee52ce1e7 | ||
|
|
00af91ea17 | ||
|
|
6fd44086b3 | ||
|
|
1a411970f9 |
@@ -1,112 +0,0 @@
|
||||
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,19 +190,12 @@ 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: |
|
||||
set -uo pipefail
|
||||
destinations=$(xcodebuild -project bitchat.xcodeproj -scheme "bitchat (iOS)" -showdestinations 2>/dev/null || true)
|
||||
destinations=$(xcodebuild -project bitchat.xcodeproj -scheme "bitchat (iOS)" -showdestinations)
|
||||
destination_id=$(awk -F'id:' '
|
||||
/platform:iOS Simulator/ && /name:iPhone/ \
|
||||
&& !/error/ && !/unavailable/ && !found {
|
||||
/platform:iOS Simulator/ && /name:iPhone/ && !found {
|
||||
value=$2
|
||||
sub(/,.*/, "", value)
|
||||
gsub(/^[[:space:]]+|[[:space:]]+$/, "", value)
|
||||
@@ -210,47 +203,10 @@ jobs:
|
||||
found=1
|
||||
}
|
||||
' <<< "$destinations")
|
||||
|
||||
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
|
||||
if [ -z "$destination_id" ]; then
|
||||
echo "::error::No available iPhone simulator destination found"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Using iPhone simulator destination id: $destination_id"
|
||||
echo "id=$destination_id" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Run iOS tests
|
||||
|
||||
+4
-9
@@ -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 6 hours so they can cross mesh partitions and survive a relaunch.
|
||||
- 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.
|
||||
- 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. 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.
|
||||
- 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.
|
||||
|
||||
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,8 +81,6 @@ 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.
|
||||
@@ -116,17 +114,14 @@ 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 6 hours.
|
||||
- **Recent public mesh gossip:** up to 15 minutes.
|
||||
- **Public board posts and tombstones:** until expiry, at most seven days.
|
||||
- **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.
|
||||
- **Groups, favorites, preferences, identity keys, bookmarks, and media:** until removed by the feature, panic wipe, quota eviction where applicable, 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,12 +8,6 @@ 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.
|
||||
@@ -24,7 +18,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 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
|
||||
- **Privacy First**: No accounts, no phone numbers, no persistent identifiers
|
||||
- **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
|
||||
@@ -40,7 +34,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 for live sessions (store-and-forward mail is sealed without it — see the whitepaper)
|
||||
- **Noise Protocol Encryption**: End-to-end encryption with forward secrecy
|
||||
- **Binary Protocol**: Compact packet format optimized for Bluetooth LE constraints
|
||||
- **Automatic Discovery**: Peer discovery and connection management
|
||||
- **Adaptive Power**: Battery-optimized duty cycling
|
||||
@@ -55,9 +49,44 @@ BitChat uses a **hybrid messaging architecture** with two complementary transpor
|
||||
|
||||
BitChat's private-envelope format is proprietary and is **not** NIP-17,
|
||||
NIP-44, or NIP-59 compatible. It uses Nostr as a relay transport but only
|
||||
interoperates with BitChat clients: private payloads travel inside kind-1059
|
||||
events whose `v2:`-prefixed content is a BitChat-specific XChaCha20-Poly1305
|
||||
construction, not NIP-44 encryption.
|
||||
interoperates with BitChat clients. New envelopes use provisional,
|
||||
BitChat-specific public kind 1402 (not a formally reserved Nostr kind),
|
||||
encrypted inner kinds 1403/1404, and the `bitchat-pm-v1:` content prefix.
|
||||
For mixed-version delivery, clients publish both the primary kind-1402
|
||||
envelope and a compatibility kind-1059 copy. There is no date-based cutoff:
|
||||
kind 1059 must remain enabled until a coordinated iOS/Android release confirms
|
||||
that supported older clients have migrated. Receivers subscribe to both kinds
|
||||
and deduplicate the authenticated embedded BitChat payload.
|
||||
|
||||
Private-envelope migration compatibility:
|
||||
|
||||
| Sender | Receiver | Delivery path |
|
||||
| --- | --- | --- |
|
||||
| New iOS | New iOS | Kind 1402 is primary; the kind-1059 twin is deduplicated |
|
||||
| New iOS | Released iOS | Compatibility kind 1059 |
|
||||
| New iOS | Current Android | Compatibility kind 1059 |
|
||||
| Released iOS | New iOS | Kind 1059 with the released empty inner-tag shape |
|
||||
| Current Android | New iOS | Kind 1059 with exactly the authenticated recipient `p` tag |
|
||||
|
||||
New kind-1402 envelopes require an empty inner tag list. The Android recipient
|
||||
tag exception is intentionally confined to legacy kind 1059 and accepts only
|
||||
the exact addressed recipient. Mailbox subscriptions cover the 24-hour
|
||||
delivery window plus Android's full 48-hour timestamp randomization and 15
|
||||
minutes of clock skew. Recovery uses
|
||||
one independent 500-event relay filter per wire kind so either format cannot
|
||||
consume the other's result budget.
|
||||
|
||||
The two outbound migration copies are admitted to the relay queue as one
|
||||
protected batch. Queue pressure evicts ephemeral traffic first, never one copy
|
||||
of a private pair; if protected capacity is exhausted, the entire new pair is
|
||||
rejected as a whole. User-message rejection becomes a visible failed delivery;
|
||||
acknowledgements and favorite notifications retain the exact pair in a
|
||||
process-wide 256-entry bounded retry queue. A sustained outage beyond that
|
||||
bound evicts the oldest whole control pair with an explicit warning, never half
|
||||
a pair.
|
||||
If either socket write fails, the same queued pair remains pending and both
|
||||
copies are replayed on the replacement connection. A terminal relay target is
|
||||
pruned after bounded retries so one dead relay cannot wedge healthy delivery.
|
||||
|
||||
### Channel Types
|
||||
|
||||
|
||||
-45
@@ -1,45 +0,0 @@
|
||||
# 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
-15
@@ -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:** 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.
|
||||
* **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.
|
||||
|
||||
## 2. Architecture Overview
|
||||
|
||||
@@ -36,17 +36,13 @@ 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 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.
|
||||
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.
|
||||
|
||||
## 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.
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
### 4.2 Flood Control
|
||||
|
||||
@@ -82,9 +78,9 @@ Courier envelopes are sealed to the recipient's *static* key with the one-way No
|
||||
|
||||
### 5.3 Nostr Path
|
||||
|
||||
Private messages to mutual favorites use BitChat's proprietary private-envelope protocol. An unsigned inner message (kind 14) is encrypted and placed in a sender-signed seal (kind 13); that seal is encrypted again inside a public envelope (kind 1059) signed by a one-time key, so relays learn neither the stable sender identity nor the content. Each encrypted content field is `v2:` followed by base64url of a 24-byte nonce, XChaCha20-Poly1305 ciphertext, and its 16-byte tag. Keys come from secp256k1 ECDH and HKDF-SHA256 (the derivation reuses a "nip44-v2" info label but is not the NIP-44 key schedule).
|
||||
Private messages to mutual favorites use BitChat's proprietary private-envelope protocol. An unsigned inner message (kind 1404) is encrypted and placed in a sender-signed seal (kind 1403); that seal is encrypted again inside a public envelope (kind 1402) signed by a one-time key. Kind 1402 is a provisional BitChat-specific assignment, not a formally reserved Nostr kind. Each encrypted content field is `bitchat-pm-v1:` followed by base64url of a 24-byte nonce, XChaCha20-Poly1305 ciphertext, and its 16-byte tag. Keys come from secp256k1 ECDH and HKDF-SHA256 with a BitChat-specific domain separator.
|
||||
|
||||
This format reuses NIP-17/NIP-59 kind numbers but is **not NIP-17, NIP-44, or NIP-59 compatible** and interoperates only with BitChat clients. The outer `p` tag exposes the recipient's Nostr public key to relays; the plaintext and stable sender identity remain inside authenticated ciphertext. Public seal and envelope timestamps are randomized by up to ±15 minutes, while the actual message timestamp is encrypted. The protocol does not provide forward secrecy: compromise of the recipient's static Nostr private key can expose stored envelopes addressed to that key.
|
||||
This format is **not NIP-17, NIP-44, or NIP-59 compatible** and interoperates only with BitChat clients. The outer `p` tag exposes the recipient's Nostr public key to relays; the stable sender identity and plaintext remain inside authenticated ciphertext. New-format seal and envelope timestamps are randomized up to 15 minutes into the past, while the actual message timestamp is encrypted. Legacy Android envelopes can carry public-layer timestamps randomized across the preceding 48 hours. The protocol does not provide forward secrecy: compromise of the recipient's static Nostr private key can expose stored envelopes.
|
||||
|
||||
## 6. Store and Forward
|
||||
|
||||
@@ -111,7 +107,11 @@ Public broadcast messages are cached (1000 packets) and reconciled between peers
|
||||
|
||||
### 6.4 Nostr Mailboxes
|
||||
|
||||
BitChat private envelopes rest on Nostr relays; clients re-subscribe with a 24-hour lookback on reconnect, covering the both-devices-offline case for mutual favorites whenever either side touches the internet.
|
||||
BitChat private envelopes rest on Nostr relays; clients re-subscribe across the 24-hour delivery window plus the full 48-hour timestamp randomization used by deployed Android clients and 15 minutes of clock skew (72 hours 15 minutes total). During the rolling format migration, clients subscribe to both the provisional BitChat-specific kind 1402 and historical kind 1059. Recovery places the kinds in separate filters within one REQ, each with an independent 500-event limit, so traffic in one format cannot starve the other. Each logical payload is published first in the primary kind-1402 format and then as a compatibility legacy copy for older iOS and current Android clients. There is no calendar cutoff: legacy publication and reception remain until a coordinated cross-platform release confirms supported clients have migrated. Bounded dedup of the authenticated embedded payload collapses the migration pair at receivers.
|
||||
|
||||
The relay send queue treats those two events as one protected batch. Capacity pressure removes ephemeral events before regular traffic and never evicts only one private-envelope copy. A queue containing only protected batches rejects a new pair as a whole: user messages surface a failed delivery, while acknowledgements and favorite notifications retain the exact pair in one process-wide 256-entry bounded-backoff retry queue shared by account and short-lived geohash transports. Sustained control-payload overflow evicts the oldest whole pair with an explicit warning rather than growing memory or splitting formats. After either socket write fails, the same pair remains pending and both copies are replayed on the replacement connection. Terminal relay targets are pruned after bounded connection retries; a batch that succeeded elsewhere retires normally, while an all-target failure returns to the transport's failure/retry policy. Receive-side dedup suppresses the replay if one copy had already reached the relay.
|
||||
|
||||
Released iOS legacy envelopes use an empty inner tag list. Current Android legacy envelopes use exactly one inner `p` tag naming the recipient. The kind-1059 decoder accepts only those two shapes after authenticating the outer recipient and sender-signed seal; alternate recipients, duplicate tags, and extra tags are rejected. Kind 1402 remains strict and permits no inner tags.
|
||||
|
||||
### 6.5 Delivery Metrics
|
||||
|
||||
@@ -128,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 opaque ciphertext. Padding applies to Noise frames only (§4.1), so other packet types relay at their natural length.
|
||||
* **Relay nodes** cannot read private traffic; they forward padded, opaque ciphertext.
|
||||
* **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 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).
|
||||
* **Metadata.** BLE proximity is inherently observable; ephemeral IDs and daily-rotating courier tags limit long-term correlation. Nostr traffic can ride Tor.
|
||||
* **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
|
||||
@@ -141,9 +141,6 @@ 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,8 +13,6 @@ 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,21 +152,11 @@ 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))
|
||||
|
||||
@@ -329,16 +319,6 @@ 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,40 +442,6 @@ 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 {
|
||||
|
||||
@@ -1,100 +0,0 @@
|
||||
//
|
||||
// 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,10 +74,7 @@ final class AppDelegate: NSObject, UIApplicationDelegate {
|
||||
weak var runtime: AppRuntime?
|
||||
|
||||
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
|
||||
// Installed before the first resign-active so the app-switcher snapshot
|
||||
// never captures an open conversation.
|
||||
PrivacyScreen.shared.install()
|
||||
return true
|
||||
true
|
||||
}
|
||||
|
||||
func applicationWillTerminate(_ application: UIApplication) {
|
||||
|
||||
@@ -14,22 +14,18 @@
|
||||
///
|
||||
/// ## Overview
|
||||
/// BitChat's identity system separates concerns across three distinct layers:
|
||||
/// 1. **Network Identity**: the 8-byte peer ID seen on air
|
||||
/// 1. **Ephemeral Identity**: Short-lived, rotatable peer IDs for privacy
|
||||
/// 2. **Cryptographic Identity**: Long-term Noise static keys for security
|
||||
/// 3. **Social Identity**: assigned names and trust relationships
|
||||
/// 3. **Social Identity**: User-assigned names and trust relationships
|
||||
///
|
||||
/// 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.
|
||||
/// This separation allows users to maintain stable cryptographic identities
|
||||
/// while frequently rotating their network identifiers for privacy.
|
||||
///
|
||||
/// ## Three-Layer Architecture
|
||||
///
|
||||
/// ### 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.
|
||||
/// ### Layer 1: Ephemeral Identity
|
||||
/// - Random 8-byte peer IDs that rotate periodically
|
||||
/// - Provides network-level privacy and prevents tracking
|
||||
/// - Changes don't affect cryptographic relationships
|
||||
/// - Includes handshake state tracking
|
||||
///
|
||||
@@ -37,7 +33,7 @@
|
||||
/// - Based on Noise Protocol static key pairs
|
||||
/// - Fingerprint derived from SHA256 of public key
|
||||
/// - Enables end-to-end encryption and authentication
|
||||
/// - The root of the peer ID above, and never rotated on a schedule
|
||||
/// - Persists across peer ID rotations
|
||||
///
|
||||
/// ### Layer 3: Social Identity
|
||||
/// - User-assigned names (petnames) for contacts
|
||||
@@ -48,13 +44,10 @@
|
||||
/// ## Privacy Design
|
||||
/// The model is designed with privacy-first principles:
|
||||
/// - No mandatory persistent storage
|
||||
/// - Optional identity caching with explicit consent
|
||||
/// - Optional identity caching with user consent
|
||||
/// - Ephemeral IDs prevent long-term tracking
|
||||
/// - 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
|
||||
@@ -63,17 +56,17 @@
|
||||
/// 4. **Verified**: Cryptographic verification completed
|
||||
///
|
||||
/// ## Identity Resolution
|
||||
/// When a peer's ID changes (a panic wipe on their side, or a future rotation):
|
||||
/// When a peer rotates their ephemeral ID:
|
||||
/// 1. Cryptographic handshake reveals their fingerprint
|
||||
/// 2. System looks up social identity by fingerprint
|
||||
/// 3. UI seamlessly maintains existing relationships
|
||||
/// 3. UI seamlessly maintains user relationships
|
||||
/// 4. Historical messages remain properly attributed
|
||||
///
|
||||
/// ## Conflict Resolution
|
||||
/// Handles edge cases like:
|
||||
/// - Multiple peers claiming same nickname
|
||||
/// - Nickname changes and conflicts
|
||||
/// - Identity replacement during active chats
|
||||
/// - Identity rotation during active chats
|
||||
/// - Network partitions and rejoins
|
||||
///
|
||||
/// ## Usage Example
|
||||
@@ -92,12 +85,8 @@ import BitFoundation
|
||||
|
||||
// MARK: - Three-Layer Identity Model
|
||||
|
||||
/// 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.
|
||||
/// 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.
|
||||
struct EphemeralIdentity {
|
||||
var handshakeState: HandshakeState
|
||||
}
|
||||
@@ -110,9 +99,8 @@ enum HandshakeState {
|
||||
}
|
||||
|
||||
/// Represents the cryptographic layer of identity - the stable Noise Protocol static key pair.
|
||||
/// 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.
|
||||
/// This identity persists across ephemeral ID rotations and enables secure communication.
|
||||
/// The fingerprint serves as the permanent identifier for a peer's cryptographic identity.
|
||||
struct CryptographicIdentity: Codable {
|
||||
let fingerprint: String // SHA256 of public key
|
||||
let publicKey: Data // Noise static public key
|
||||
|
||||
+185
-3534
File diff suppressed because it is too large
Load Diff
@@ -75,19 +75,7 @@ private extension GeoRelayDirectoryDependencies {
|
||||
refreshCheckInterval: TransportConfig.geoRelayRefreshCheckIntervalSeconds,
|
||||
retryInitialSeconds: TransportConfig.geoRelayRetryInitialSeconds,
|
||||
retryMaxSeconds: TransportConfig.geoRelayRetryMaxSeconds,
|
||||
// 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()
|
||||
},
|
||||
awaitTorReady: { await TorManager.shared.awaitReady() },
|
||||
makeFetchData: {
|
||||
let session = TorURLSession.shared.session
|
||||
return { request in
|
||||
|
||||
+399
-286
@@ -9,24 +9,29 @@ import Security
|
||||
|
||||
/// BitChat's private-envelope protocol transported over Nostr relays.
|
||||
///
|
||||
/// This construction is deliberately BitChat-specific and is **not** NIP-17,
|
||||
/// NIP-44, or NIP-59 compatible, even though it historically reuses those
|
||||
/// NIPs' kind numbers (1059/13/14) and a `v2:` content prefix. It uses Nostr
|
||||
/// events and secp256k1 identities, but the XChaCha20-Poly1305 payload layout
|
||||
/// and key derivation are proprietary and interoperate only with BitChat
|
||||
/// clients.
|
||||
/// This is deliberately BitChat-specific and is not NIP-17, NIP-44, or NIP-59.
|
||||
/// It uses Nostr events and secp256k1 identities, but its XChaCha20-Poly1305
|
||||
/// payload layout is proprietary and interoperates only with BitChat clients.
|
||||
struct NostrProtocol {
|
||||
|
||||
|
||||
/// Nostr event kinds
|
||||
enum EventKind: Int {
|
||||
case metadata = 0
|
||||
case textNote = 1
|
||||
// BitChat's proprietary private-envelope layers. These reuse the
|
||||
// NIP-17/NIP-59 kind numbers (14/13/1059) for historical reasons, but
|
||||
// the encrypted payloads are BitChat-specific and not NIP-compatible.
|
||||
case dm = 14 // unsigned inner message (inside ciphertext)
|
||||
case seal = 13 // sender-signed seal (inside ciphertext)
|
||||
case giftWrap = 1059 // public outer envelope (one-time key)
|
||||
// Compatibility for BitChat releases that incorrectly emitted the
|
||||
// proprietary payload under standard NIP kinds. Kind 1059 continues
|
||||
// to be published and read until a coordinated cross-platform release
|
||||
// explicitly removes it; all three legacy layers remain readable.
|
||||
case legacyNIP59Seal = 13
|
||||
case legacyNIP17DirectMessage = 14
|
||||
case legacyNIP59GiftWrap = 1059
|
||||
// Provisional BitChat-specific regular event kinds. These are not
|
||||
// formally reserved by the Nostr kind registry. Only
|
||||
// `privateEnvelope` is published; message and seal exist solely
|
||||
// inside ciphertext.
|
||||
case privateEnvelope = 1402
|
||||
case privateSeal = 1403
|
||||
case privateMessage = 1404
|
||||
case ephemeralEvent = 20000
|
||||
case geohashPresence = 20001
|
||||
case deletion = 5 // NIP-09 event deletion request
|
||||
@@ -36,209 +41,290 @@ struct NostrProtocol {
|
||||
case courierDrop = 1401
|
||||
}
|
||||
|
||||
/// Bound work before Base64-decoding either encrypted layer of an inbound
|
||||
/// private envelope, and before parsing each decrypted nested JSON layer.
|
||||
/// Real envelopes are normally a few KiB; 64 KiB leaves ample headroom
|
||||
/// without letting an addressed relay event drive unbounded allocation.
|
||||
/// Prefix for BitChat private-envelope ciphertext. The suffix is
|
||||
/// base64url(nonce24 || ciphertext || poly1305Tag).
|
||||
static let privateEnvelopeContentPrefix = "bitchat-pm-v1:"
|
||||
|
||||
/// Bound work before Base64 decoding either encrypted layer. Current
|
||||
/// private messages are normally only a few KiB; 64 KiB leaves ample
|
||||
/// migration headroom without allowing an addressed relay event to drive
|
||||
/// unbounded allocation.
|
||||
static let maximumPrivateEnvelopeCiphertextBytes = 64 * 1024
|
||||
|
||||
/// Create a BitChat private envelope for relay transport (outer kind 1059).
|
||||
static func createPrivateMessage(
|
||||
/// Bound the inner authenticated message JSON before allocation/parsing.
|
||||
/// This is intentionally an envelope limit, not the generic composer
|
||||
/// limit. Raising it alone would not make larger private-message packets
|
||||
/// compatible with released readers; callers must surface a rejected
|
||||
/// packet or envelope as a failed send.
|
||||
static let maximumPrivateEnvelopePlaintextBytes = 32 * 1024
|
||||
|
||||
/// The outer authenticated seal JSON contains a Base64-encoded encrypted
|
||||
/// copy of the inner JSON, so it needs expansion headroom of its own. Keep
|
||||
/// the layer-specific cap below the public ciphertext ceiling.
|
||||
private static let maximumPrivateEnvelopeSealPlaintextBytes = 48 * 1024
|
||||
|
||||
/// New clients subscribe to the provisional BitChat-specific kind and the
|
||||
/// compatibility legacy kind so both sides of a rolling rollout can
|
||||
/// recover stored messages. Do not remove kind 1059 here until all
|
||||
/// supported iOS and Android releases have migrated.
|
||||
static let acceptedPrivateEnvelopeKinds = [
|
||||
EventKind.privateEnvelope.rawValue,
|
||||
EventKind.legacyNIP59GiftWrap.rawValue
|
||||
]
|
||||
|
||||
private enum PrivateEnvelopeWireFormat {
|
||||
case bitchatV1
|
||||
case legacyMislabelledV2
|
||||
|
||||
init?(outerKind: Int) {
|
||||
switch outerKind {
|
||||
case EventKind.privateEnvelope.rawValue:
|
||||
self = .bitchatV1
|
||||
case EventKind.legacyNIP59GiftWrap.rawValue:
|
||||
self = .legacyMislabelledV2
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
var messageKind: EventKind {
|
||||
switch self {
|
||||
case .bitchatV1: .privateMessage
|
||||
case .legacyMislabelledV2: .legacyNIP17DirectMessage
|
||||
}
|
||||
}
|
||||
|
||||
var sealKind: EventKind {
|
||||
switch self {
|
||||
case .bitchatV1: .privateSeal
|
||||
case .legacyMislabelledV2: .legacyNIP59Seal
|
||||
}
|
||||
}
|
||||
|
||||
var envelopeKind: EventKind {
|
||||
switch self {
|
||||
case .bitchatV1: .privateEnvelope
|
||||
case .legacyMislabelledV2: .legacyNIP59GiftWrap
|
||||
}
|
||||
}
|
||||
|
||||
var contentPrefix: String {
|
||||
switch self {
|
||||
case .bitchatV1: NostrProtocol.privateEnvelopeContentPrefix
|
||||
case .legacyMislabelledV2: "v2:"
|
||||
}
|
||||
}
|
||||
|
||||
var hkdfSalt: Data {
|
||||
switch self {
|
||||
case .bitchatV1: Data("bitchat-private-envelope-v1".utf8)
|
||||
case .legacyMislabelledV2: Data()
|
||||
}
|
||||
}
|
||||
|
||||
var hkdfInfo: Data {
|
||||
switch self {
|
||||
case .bitchatV1: Data()
|
||||
case .legacyMislabelledV2: Data("nip44-v2".utf8)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a BitChat private envelope for relay transport.
|
||||
static func createPrivateEnvelope(
|
||||
content: String,
|
||||
recipientPubkey: String,
|
||||
senderIdentity: NostrIdentity
|
||||
) throws -> NostrEvent {
|
||||
try createPrivateMessage(
|
||||
try createPrivateEnvelope(
|
||||
content: content,
|
||||
recipientPubkey: recipientPubkey,
|
||||
senderIdentity: senderIdentity,
|
||||
messageTags: []
|
||||
format: .bitchatV1
|
||||
)
|
||||
}
|
||||
|
||||
private static func createPrivateMessage(
|
||||
/// Events to publish for one logical private payload. The primary
|
||||
/// BitChat-specific format is always first and a legacy copy follows for
|
||||
/// clients that still subscribe only to kind 1059. There is deliberately
|
||||
/// no date-based cutoff: removal requires a coordinated iOS/Android
|
||||
/// release after supported old clients have migrated. Both encrypt the
|
||||
/// exact same embedded BitChat payload, so receive-side logical-payload
|
||||
/// dedup collapses the pair.
|
||||
static func createPrivateEnvelopePublicationBatch(
|
||||
content: String,
|
||||
recipientPubkey: String,
|
||||
senderIdentity: NostrIdentity
|
||||
) throws -> [NostrEvent] {
|
||||
let primary = try createPrivateEnvelope(
|
||||
content: content,
|
||||
recipientPubkey: recipientPubkey,
|
||||
senderIdentity: senderIdentity
|
||||
)
|
||||
let compatibilityCopy = try createPrivateEnvelope(
|
||||
content: content,
|
||||
recipientPubkey: recipientPubkey,
|
||||
senderIdentity: senderIdentity,
|
||||
format: .legacyMislabelledV2
|
||||
)
|
||||
return [primary, compatibilityCopy]
|
||||
}
|
||||
|
||||
private static func createPrivateEnvelope(
|
||||
content: String,
|
||||
recipientPubkey: String,
|
||||
senderIdentity: NostrIdentity,
|
||||
messageTags: [[String]]
|
||||
format: PrivateEnvelopeWireFormat,
|
||||
messageTags: [[String]] = []
|
||||
) throws -> NostrEvent {
|
||||
// 1. Create the rumor (unsigned inner event)
|
||||
let rumor = NostrEvent(
|
||||
// 1. Create the unsigned inner BitChat message.
|
||||
let message = NostrEvent(
|
||||
pubkey: senderIdentity.publicKeyHex,
|
||||
createdAt: Date(),
|
||||
kind: .dm,
|
||||
kind: format.messageKind,
|
||||
tags: messageTags,
|
||||
content: content
|
||||
)
|
||||
|
||||
// 2. Seal the rumor (encrypt to recipient) and sign it with the SENDER'S
|
||||
// real identity key so the recipient can authenticate who sent the
|
||||
// message; signing with a throwaway key leaves DMs
|
||||
// forgeable/impersonatable.
|
||||
|
||||
// 2. Encrypt the message to the recipient and sign the private seal
|
||||
// with the sender's stable Nostr identity for sender authentication.
|
||||
let senderKey = try senderIdentity.schnorrSigningKey()
|
||||
let sealedEvent = try createSeal(
|
||||
rumor: rumor,
|
||||
let sealedEvent = try createPrivateSeal(
|
||||
message: message,
|
||||
recipientPubkey: recipientPubkey,
|
||||
senderKey: senderKey
|
||||
senderKey: senderKey,
|
||||
format: format
|
||||
)
|
||||
|
||||
// 3. Wrap the sealed event with a throwaway ephemeral key (the wrap
|
||||
// layer hides the sender's identity from relays; createGiftWrap mints
|
||||
// its own ephemeral key internally).
|
||||
let giftWrap = try createGiftWrap(
|
||||
// 3. Encrypt the seal under a one-time key so the public envelope does
|
||||
// not reveal the stable sender identity.
|
||||
return try createPrivateEnvelopeEvent(
|
||||
seal: sealedEvent,
|
||||
recipientPubkey: recipientPubkey
|
||||
recipientPubkey: recipientPubkey,
|
||||
format: format
|
||||
)
|
||||
|
||||
return giftWrap
|
||||
}
|
||||
|
||||
/// Decrypt a received BitChat private envelope.
|
||||
/// Returns the content, sender pubkey, and the actual message timestamp (not the randomized outer timestamp)
|
||||
static func decryptPrivateMessage(
|
||||
giftWrap: NostrEvent,
|
||||
|
||||
/// Decrypt a BitChat private envelope. Legacy proprietary envelopes that
|
||||
/// older BitChat releases placed under kinds 1059/13/14 are accepted only
|
||||
/// through the format-isolated receive path.
|
||||
static func decryptPrivateEnvelope(
|
||||
envelope: NostrEvent,
|
||||
recipientIdentity: NostrIdentity
|
||||
) throws -> (content: String, senderPubkey: String, timestamp: Int) {
|
||||
|
||||
// 0. Validate the untrusted outer envelope before any decryption work.
|
||||
// Every BitChat client (released iOS and current Android) publishes
|
||||
// exactly one outer recipient `p` tag on a validly signed kind-1059
|
||||
// wrap; anything else is malformed or misbound.
|
||||
guard giftWrap.content.utf8.count <= maximumPrivateEnvelopeCiphertextBytes else {
|
||||
SecureLogger.error("❌ Rejecting DM: oversized outer envelope ciphertext", category: .session)
|
||||
throw NostrError.invalidCiphertext
|
||||
}
|
||||
guard giftWrap.kind == EventKind.giftWrap.rawValue,
|
||||
giftWrap.tags == [["p", recipientIdentity.publicKeyHex]],
|
||||
giftWrap.isValidSignature() else {
|
||||
SecureLogger.error("❌ Rejecting DM: malformed or misbound outer envelope", category: .session)
|
||||
throw NostrError.invalidEvent
|
||||
}
|
||||
|
||||
// 1. Unwrap the gift wrap
|
||||
let seal: NostrEvent
|
||||
do {
|
||||
seal = try unwrapGiftWrap(
|
||||
giftWrap: giftWrap,
|
||||
recipientKey: recipientIdentity.schnorrSigningKey()
|
||||
)
|
||||
// Successfully unwrapped gift wrap
|
||||
} catch {
|
||||
SecureLogger.error("❌ Failed to unwrap gift wrap: \(error)", category: .session)
|
||||
throw error
|
||||
}
|
||||
|
||||
// 2. Authenticate the seal. The seal MUST be signed by the sender's real
|
||||
// identity key; without this check a DM is forgeable by anyone who
|
||||
// knows the recipient's npub. Every BitChat sender emits a tagless
|
||||
// kind-13 seal, so bind the decrypted layer to that exact shape.
|
||||
guard seal.kind == EventKind.seal.rawValue,
|
||||
seal.tags.isEmpty,
|
||||
seal.isValidSignature() else {
|
||||
SecureLogger.error("❌ Rejecting DM: seal is malformed or its signature is missing/invalid", category: .session)
|
||||
throw NostrError.invalidEvent
|
||||
}
|
||||
|
||||
// 3. Open the seal
|
||||
let rumor: NostrEvent
|
||||
do {
|
||||
rumor = try openSeal(
|
||||
seal: seal,
|
||||
recipientKey: recipientIdentity.schnorrSigningKey()
|
||||
)
|
||||
// Successfully opened seal
|
||||
} catch {
|
||||
SecureLogger.error("❌ Failed to open seal: \(error)", category: .session)
|
||||
throw error
|
||||
}
|
||||
|
||||
// 4. The rumor is intentionally unsigned; sender authentication comes
|
||||
// from the seal. The sender claimed inside the rumor must match the
|
||||
// key that actually signed the seal, otherwise the sender field is
|
||||
// unauthenticated and spoofable. Also bind the inner kind and tag
|
||||
// shape to what BitChat clients actually emit.
|
||||
guard rumor.kind == EventKind.dm.rawValue,
|
||||
validInnerMessageTags(rumor.tags, recipientPubkey: recipientIdentity.publicKeyHex),
|
||||
rumor.sig == nil,
|
||||
seal.pubkey == rumor.pubkey else {
|
||||
SecureLogger.error("❌ Rejecting DM: rumor is malformed or does not match seal signer", category: .session)
|
||||
throw NostrError.invalidEvent
|
||||
}
|
||||
|
||||
// Return the seal signer's pubkey as the authenticated sender.
|
||||
return (content: rumor.content, senderPubkey: seal.pubkey, timestamp: rumor.created_at)
|
||||
}
|
||||
|
||||
/// Released iOS envelopes use no inner tags, while current Android
|
||||
/// envelopes place exactly the authenticated recipient's `p` tag on the
|
||||
/// unsigned inner event. Accept only those two historical shapes;
|
||||
/// alternate recipients, duplicate tags, and extra tags are rejected.
|
||||
private static func validInnerMessageTags(
|
||||
_ tags: [[String]],
|
||||
recipientPubkey: String
|
||||
) -> Bool {
|
||||
tags.isEmpty || tags == [["p", recipientPubkey]]
|
||||
let layers = try decodePrivateEnvelopeLayers(
|
||||
envelope: envelope,
|
||||
recipientIdentity: recipientIdentity
|
||||
)
|
||||
return (
|
||||
content: layers.message.content,
|
||||
senderPubkey: layers.seal.pubkey,
|
||||
timestamp: layers.message.created_at
|
||||
)
|
||||
}
|
||||
|
||||
#if DEBUG
|
||||
static func createPrivateMessageWithInvalidSealSignatureForTesting(
|
||||
static func createPrivateEnvelopeWithInvalidSealSignatureForTesting(
|
||||
content: String,
|
||||
recipientPubkey: String,
|
||||
senderIdentity: NostrIdentity
|
||||
) throws -> NostrEvent {
|
||||
let rumor = NostrEvent(
|
||||
let format = PrivateEnvelopeWireFormat.bitchatV1
|
||||
let message = NostrEvent(
|
||||
pubkey: senderIdentity.publicKeyHex,
|
||||
createdAt: Date(),
|
||||
kind: .dm,
|
||||
kind: format.messageKind,
|
||||
tags: [],
|
||||
content: content
|
||||
)
|
||||
var seal = try createSeal(
|
||||
rumor: rumor,
|
||||
var seal = try createPrivateSeal(
|
||||
message: message,
|
||||
recipientPubkey: recipientPubkey,
|
||||
senderKey: senderIdentity.schnorrSigningKey()
|
||||
senderKey: senderIdentity.schnorrSigningKey(),
|
||||
format: format
|
||||
)
|
||||
seal.sig = String(repeating: "0", count: 128)
|
||||
return try createGiftWrap(seal: seal, recipientPubkey: recipientPubkey)
|
||||
return try createPrivateEnvelopeEvent(
|
||||
seal: seal,
|
||||
recipientPubkey: recipientPubkey,
|
||||
format: format
|
||||
)
|
||||
}
|
||||
|
||||
static func createPrivateMessageWithMismatchedSealRumorPubkeyForTesting(
|
||||
static func createPrivateEnvelopeWithMismatchedSealMessagePubkeyForTesting(
|
||||
content: String,
|
||||
recipientPubkey: String,
|
||||
rumorIdentity: NostrIdentity,
|
||||
messageIdentity: NostrIdentity,
|
||||
sealSignerIdentity: NostrIdentity
|
||||
) throws -> NostrEvent {
|
||||
let rumor = NostrEvent(
|
||||
pubkey: rumorIdentity.publicKeyHex,
|
||||
let format = PrivateEnvelopeWireFormat.bitchatV1
|
||||
let message = NostrEvent(
|
||||
pubkey: messageIdentity.publicKeyHex,
|
||||
createdAt: Date(),
|
||||
kind: .dm,
|
||||
kind: format.messageKind,
|
||||
tags: [],
|
||||
content: content
|
||||
)
|
||||
let seal = try createSeal(
|
||||
rumor: rumor,
|
||||
let seal = try createPrivateSeal(
|
||||
message: message,
|
||||
recipientPubkey: recipientPubkey,
|
||||
senderKey: sealSignerIdentity.schnorrSigningKey()
|
||||
senderKey: sealSignerIdentity.schnorrSigningKey(),
|
||||
format: format
|
||||
)
|
||||
return try createPrivateEnvelopeEvent(
|
||||
seal: seal,
|
||||
recipientPubkey: recipientPubkey,
|
||||
format: format
|
||||
)
|
||||
return try createGiftWrap(seal: seal, recipientPubkey: recipientPubkey)
|
||||
}
|
||||
|
||||
/// Reproduces historical wire shapes (current Android places exactly one
|
||||
/// recipient `p` tag on the unsigned inner event) without making the
|
||||
/// production encoder depend on that quirk.
|
||||
static func createPrivateMessageWithInnerTagsForTesting(
|
||||
static func createPrivateEnvelopeWithInnerTagsForTesting(
|
||||
content: String,
|
||||
recipientPubkey: String,
|
||||
senderIdentity: NostrIdentity,
|
||||
innerMessageTags: [[String]]
|
||||
) throws -> NostrEvent {
|
||||
try createPrivateMessage(
|
||||
try createPrivateEnvelope(
|
||||
content: content,
|
||||
recipientPubkey: recipientPubkey,
|
||||
senderIdentity: senderIdentity,
|
||||
format: .bitchatV1,
|
||||
messageTags: innerMessageTags
|
||||
)
|
||||
}
|
||||
|
||||
static func createLegacyPrivateEnvelopeForTesting(
|
||||
content: String,
|
||||
recipientPubkey: String,
|
||||
senderIdentity: NostrIdentity,
|
||||
innerMessageTags: [[String]] = []
|
||||
) throws -> NostrEvent {
|
||||
// Current Android legacy envelopes use exactly one recipient `p` tag
|
||||
// on the unsigned inner kind-14 event; released iOS envelopes use no
|
||||
// inner tags. Tests pass the Android shape explicitly so this helper
|
||||
// cannot silently make the production encoder depend on that quirk.
|
||||
try createPrivateEnvelope(
|
||||
content: content,
|
||||
recipientPubkey: recipientPubkey,
|
||||
senderIdentity: senderIdentity,
|
||||
format: .legacyMislabelledV2,
|
||||
messageTags: innerMessageTags
|
||||
)
|
||||
}
|
||||
|
||||
static func decodePrivateEnvelopeLayersForTesting(
|
||||
envelope: NostrEvent,
|
||||
recipientIdentity: NostrIdentity
|
||||
) throws -> (seal: NostrEvent, message: NostrEvent) {
|
||||
try decodePrivateEnvelopeLayers(
|
||||
envelope: envelope,
|
||||
recipientIdentity: recipientIdentity
|
||||
)
|
||||
}
|
||||
|
||||
static func decodePrivateEnvelopeEventJSONForTesting(_ json: String) throws -> NostrEvent {
|
||||
try decodePrivateEnvelopeEventJSON(json)
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Create a geohash-scoped ephemeral public message (kind 20000)
|
||||
@@ -474,170 +560,211 @@ struct NostrProtocol {
|
||||
|
||||
// MARK: - Private Methods
|
||||
|
||||
private static func createSeal(
|
||||
rumor: NostrEvent,
|
||||
private static func createPrivateSeal(
|
||||
message: NostrEvent,
|
||||
recipientPubkey: String,
|
||||
senderKey: P256K.Schnorr.PrivateKey
|
||||
senderKey: P256K.Schnorr.PrivateKey,
|
||||
format: PrivateEnvelopeWireFormat
|
||||
) throws -> NostrEvent {
|
||||
|
||||
let rumorJSON = try rumor.jsonString()
|
||||
let encrypted = try encrypt(
|
||||
plaintext: rumorJSON,
|
||||
plaintext: message.jsonString(),
|
||||
recipientPubkey: recipientPubkey,
|
||||
senderKey: senderKey
|
||||
senderKey: senderKey,
|
||||
format: format,
|
||||
maximumPlaintextBytes: maximumPrivateEnvelopePlaintextBytes
|
||||
)
|
||||
|
||||
|
||||
let seal = NostrEvent(
|
||||
pubkey: Data(senderKey.xonly.bytes).hexEncodedString(),
|
||||
createdAt: randomizedTimestamp(),
|
||||
kind: .seal,
|
||||
createdAt: randomizedPastTimestamp(),
|
||||
kind: format.sealKind,
|
||||
tags: [],
|
||||
content: encrypted
|
||||
)
|
||||
|
||||
// Sign the seal with the sender's Schnorr private key
|
||||
return try seal.sign(with: senderKey)
|
||||
}
|
||||
|
||||
private static func createGiftWrap(
|
||||
seal: NostrEvent,
|
||||
recipientPubkey: String
|
||||
) throws -> NostrEvent {
|
||||
|
||||
let sealJSON = try seal.jsonString()
|
||||
|
||||
// Create new ephemeral key for gift wrap
|
||||
let wrapKey = try P256K.Schnorr.PrivateKey()
|
||||
// Creating gift wrap with ephemeral key
|
||||
|
||||
// Encrypt the seal with the new ephemeral key (not the seal's key)
|
||||
private static func createPrivateEnvelopeEvent(
|
||||
seal: NostrEvent,
|
||||
recipientPubkey: String,
|
||||
format: PrivateEnvelopeWireFormat
|
||||
) throws -> NostrEvent {
|
||||
// A fresh signing/encryption key for every public envelope keeps the
|
||||
// stable sender identity inside ciphertext.
|
||||
let envelopeKey = try P256K.Schnorr.PrivateKey()
|
||||
let encrypted = try encrypt(
|
||||
plaintext: sealJSON,
|
||||
plaintext: seal.jsonString(),
|
||||
recipientPubkey: recipientPubkey,
|
||||
senderKey: wrapKey // Use the gift wrap ephemeral key
|
||||
senderKey: envelopeKey,
|
||||
format: format,
|
||||
maximumPlaintextBytes: maximumPrivateEnvelopeSealPlaintextBytes
|
||||
)
|
||||
|
||||
let giftWrap = NostrEvent(
|
||||
pubkey: Data(wrapKey.xonly.bytes).hexEncodedString(),
|
||||
createdAt: randomizedTimestamp(),
|
||||
kind: .giftWrap,
|
||||
tags: [["p", recipientPubkey]], // Tag recipient
|
||||
|
||||
let envelope = NostrEvent(
|
||||
pubkey: Data(envelopeKey.xonly.bytes).hexEncodedString(),
|
||||
createdAt: randomizedPastTimestamp(),
|
||||
kind: format.envelopeKind,
|
||||
tags: [["p", recipientPubkey]],
|
||||
content: encrypted
|
||||
)
|
||||
|
||||
// Sign the gift wrap with the wrap Schnorr private key
|
||||
return try giftWrap.sign(with: wrapKey)
|
||||
return try envelope.sign(with: envelopeKey)
|
||||
}
|
||||
|
||||
private static func unwrapGiftWrap(
|
||||
giftWrap: NostrEvent,
|
||||
recipientKey: P256K.Schnorr.PrivateKey
|
||||
) throws -> NostrEvent {
|
||||
|
||||
// Unwrapping gift wrap
|
||||
|
||||
let decrypted = try decrypt(
|
||||
ciphertext: giftWrap.content,
|
||||
senderPubkey: giftWrap.pubkey,
|
||||
recipientKey: recipientKey
|
||||
)
|
||||
|
||||
// Check UTF-8 size before allocating Data or invoking the general
|
||||
// JSON parser on attacker-influenced plaintext.
|
||||
guard decrypted.utf8.count <= maximumPrivateEnvelopeCiphertextBytes else {
|
||||
|
||||
private static func decodePrivateEnvelopeLayers(
|
||||
envelope: NostrEvent,
|
||||
recipientIdentity: NostrIdentity
|
||||
) throws -> (seal: NostrEvent, message: NostrEvent) {
|
||||
guard envelope.content.utf8.count <= maximumPrivateEnvelopeCiphertextBytes else {
|
||||
SecureLogger.error("❌ Rejecting DM: oversized outer envelope ciphertext", category: .session)
|
||||
throw NostrError.invalidCiphertext
|
||||
}
|
||||
guard let data = decrypted.data(using: .utf8),
|
||||
let sealDict = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
|
||||
guard let format = PrivateEnvelopeWireFormat(outerKind: envelope.kind),
|
||||
envelope.tags == [["p", recipientIdentity.publicKeyHex]],
|
||||
envelope.isValidSignature() else {
|
||||
SecureLogger.error("❌ Rejecting DM: malformed or misbound outer envelope", category: .session)
|
||||
throw NostrError.invalidEvent
|
||||
}
|
||||
|
||||
let seal = try NostrEvent(from: sealDict)
|
||||
// Unwrapped seal
|
||||
let recipientKey = try recipientIdentity.schnorrSigningKey()
|
||||
let sealJSON = try decrypt(
|
||||
ciphertext: envelope.content,
|
||||
senderPubkey: envelope.pubkey,
|
||||
recipientKey: recipientKey,
|
||||
format: format,
|
||||
maximumPlaintextBytes: maximumPrivateEnvelopeSealPlaintextBytes
|
||||
)
|
||||
let seal = try decodePrivateEnvelopeEventJSON(
|
||||
sealJSON,
|
||||
maximumBytes: maximumPrivateEnvelopeSealPlaintextBytes
|
||||
)
|
||||
guard seal.kind == format.sealKind.rawValue,
|
||||
seal.tags.isEmpty,
|
||||
seal.isValidSignature() else {
|
||||
SecureLogger.error("❌ Rejecting DM: seal is malformed or its signature is missing/invalid", category: .session)
|
||||
throw NostrError.invalidEvent
|
||||
}
|
||||
|
||||
return seal
|
||||
}
|
||||
|
||||
private static func openSeal(
|
||||
seal: NostrEvent,
|
||||
recipientKey: P256K.Schnorr.PrivateKey
|
||||
) throws -> NostrEvent {
|
||||
|
||||
let decrypted = try decrypt(
|
||||
let messageJSON = try decrypt(
|
||||
ciphertext: seal.content,
|
||||
senderPubkey: seal.pubkey,
|
||||
recipientKey: recipientKey
|
||||
recipientKey: recipientKey,
|
||||
format: format,
|
||||
maximumPlaintextBytes: maximumPrivateEnvelopePlaintextBytes
|
||||
)
|
||||
|
||||
guard decrypted.utf8.count <= maximumPrivateEnvelopeCiphertextBytes else {
|
||||
throw NostrError.invalidCiphertext
|
||||
}
|
||||
guard let data = decrypted.data(using: .utf8),
|
||||
let rumorDict = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
|
||||
let message = try decodePrivateEnvelopeEventJSON(
|
||||
messageJSON,
|
||||
maximumBytes: maximumPrivateEnvelopePlaintextBytes
|
||||
)
|
||||
|
||||
// The inner message is intentionally unsigned; sender authentication
|
||||
// comes from the seal. Bind its claimed sender and custom kind to that
|
||||
// authenticated layer before exposing content.
|
||||
guard message.kind == format.messageKind.rawValue,
|
||||
validInnerMessageTags(
|
||||
message.tags,
|
||||
format: format,
|
||||
recipientPubkey: recipientIdentity.publicKeyHex
|
||||
),
|
||||
message.sig == nil,
|
||||
seal.pubkey == message.pubkey else {
|
||||
SecureLogger.error("❌ Rejecting DM: inner message is malformed or does not match seal signer", category: .session)
|
||||
throw NostrError.invalidEvent
|
||||
}
|
||||
|
||||
return try NostrEvent(from: rumorDict)
|
||||
return (seal, message)
|
||||
}
|
||||
|
||||
/// Released iOS legacy envelopes used no inner tags, while current
|
||||
/// Android legacy envelopes use exactly the authenticated recipient tag.
|
||||
/// Accept only those two historical shapes for kind 1059. The new kind
|
||||
/// 1402 format remains strict and rejects every inner tag.
|
||||
private static func validInnerMessageTags(
|
||||
_ tags: [[String]],
|
||||
format: PrivateEnvelopeWireFormat,
|
||||
recipientPubkey: String
|
||||
) -> Bool {
|
||||
switch format {
|
||||
case .bitchatV1:
|
||||
return tags.isEmpty
|
||||
case .legacyMislabelledV2:
|
||||
return tags.isEmpty || tags == [["p", recipientPubkey]]
|
||||
}
|
||||
}
|
||||
|
||||
private static func decodePrivateEnvelopeEventJSON(
|
||||
_ json: String,
|
||||
maximumBytes: Int = maximumPrivateEnvelopePlaintextBytes
|
||||
) throws -> NostrEvent {
|
||||
// Check UTF-8 size before allocating Data or invoking the general JSON
|
||||
// parser. `decrypt` enforces the same cap on authenticated bytes; this
|
||||
// local guard keeps the parser boundary explicit and independently
|
||||
// testable.
|
||||
guard json.utf8.count <= maximumBytes else {
|
||||
throw NostrError.invalidCiphertext
|
||||
}
|
||||
guard let data = json.data(using: .utf8),
|
||||
let dictionary = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
|
||||
throw NostrError.invalidEvent
|
||||
}
|
||||
return try NostrEvent(from: dictionary)
|
||||
}
|
||||
|
||||
// MARK: - BitChat private-envelope encryption
|
||||
//
|
||||
// Not NIP-44: the `v2:` prefix, base64url(nonce24 || ciphertext || tag)
|
||||
// layout, XChaCha20-Poly1305 cipher, and HKDF parameters are all
|
||||
// BitChat-specific.
|
||||
|
||||
private static func encrypt(
|
||||
plaintext: String,
|
||||
recipientPubkey: String,
|
||||
senderKey: P256K.Schnorr.PrivateKey
|
||||
senderKey: P256K.Schnorr.PrivateKey,
|
||||
format: PrivateEnvelopeWireFormat,
|
||||
maximumPlaintextBytes: Int
|
||||
) throws -> String {
|
||||
|
||||
guard let recipientPubkeyData = Data(hexString: recipientPubkey) else {
|
||||
throw NostrError.invalidPublicKey
|
||||
}
|
||||
|
||||
// Derive shared secret
|
||||
|
||||
let sharedSecret = try deriveSharedSecret(
|
||||
privateKey: senderKey,
|
||||
publicKey: recipientPubkeyData
|
||||
)
|
||||
// Derive the BitChat private-envelope symmetric key (HKDF-SHA256)
|
||||
let key = try derivePrivateEnvelopeKey(from: sharedSecret)
|
||||
let key = derivePrivateEnvelopeKey(from: sharedSecret, format: format)
|
||||
|
||||
// 24-byte random nonce for XChaCha20-Poly1305
|
||||
var nonce24 = Data(count: 24)
|
||||
let randomStatus = nonce24.withUnsafeMutableBytes { ptr in
|
||||
SecRandomCopyBytes(kSecRandomDefault, 24, ptr.baseAddress!)
|
||||
}
|
||||
// Never encrypt with an unrandomized nonce: nonce reuse under the same
|
||||
// key breaks XChaCha20-Poly1305 confidentiality and authenticity.
|
||||
guard randomStatus == errSecSuccess else {
|
||||
throw NostrError.cryptographicFailure
|
||||
}
|
||||
|
||||
let pt = Data(plaintext.utf8)
|
||||
let sealed = try XChaCha20Poly1305Compat.seal(plaintext: pt, key: key, nonce24: nonce24)
|
||||
|
||||
// v2: base64url(nonce24 || ciphertext || tag)
|
||||
let plaintextData = Data(plaintext.utf8)
|
||||
guard plaintextData.count <= maximumPlaintextBytes else {
|
||||
throw NostrError.invalidCiphertext
|
||||
}
|
||||
let sealed = try XChaCha20Poly1305Compat.seal(
|
||||
plaintext: plaintextData,
|
||||
key: key,
|
||||
nonce24: nonce24
|
||||
)
|
||||
|
||||
var combined = Data()
|
||||
combined.append(nonce24)
|
||||
combined.append(sealed.ciphertext)
|
||||
combined.append(sealed.tag)
|
||||
return "v2:" + Base64URLCoding.encode(combined)
|
||||
return format.contentPrefix + Base64URLCoding.encode(combined)
|
||||
}
|
||||
|
||||
|
||||
private static func decrypt(
|
||||
ciphertext: String,
|
||||
senderPubkey: String,
|
||||
recipientKey: P256K.Schnorr.PrivateKey
|
||||
recipientKey: P256K.Schnorr.PrivateKey,
|
||||
format: PrivateEnvelopeWireFormat,
|
||||
maximumPlaintextBytes: Int
|
||||
) throws -> String {
|
||||
// Expect BitChat's historical `v2:` private-envelope framing, and
|
||||
// bound work before Base64 decoding attacker-sized input.
|
||||
guard ciphertext.utf8.count <= maximumPrivateEnvelopeCiphertextBytes,
|
||||
ciphertext.hasPrefix("v2:") else {
|
||||
ciphertext.hasPrefix(format.contentPrefix) else {
|
||||
throw NostrError.invalidCiphertext
|
||||
}
|
||||
let encoded = String(ciphertext.dropFirst(3))
|
||||
let encoded = String(ciphertext.dropFirst(format.contentPrefix.count))
|
||||
guard let data = Base64URLCoding.decode(encoded),
|
||||
data.count > (24 + 16),
|
||||
let senderPubkeyData = Data(hexString: senderPubkey) else {
|
||||
@@ -647,37 +774,37 @@ struct NostrProtocol {
|
||||
let nonce24 = data.prefix(24)
|
||||
let rest = data.dropFirst(24)
|
||||
let tag = rest.suffix(16)
|
||||
let ct = rest.dropLast(16)
|
||||
let ciphertextBytes = rest.dropLast(16)
|
||||
|
||||
// Try decryption with even-Y then odd-Y when sender pubkey is x-only
|
||||
func attemptDecrypt(using pubKeyData: Data) throws -> Data {
|
||||
let ss = try deriveSharedSecret(privateKey: recipientKey, publicKey: pubKeyData)
|
||||
let key = try derivePrivateEnvelopeKey(from: ss)
|
||||
func attemptDecrypt(using publicKeyData: Data) throws -> Data {
|
||||
let sharedSecret = try deriveSharedSecret(
|
||||
privateKey: recipientKey,
|
||||
publicKey: publicKeyData
|
||||
)
|
||||
let key = derivePrivateEnvelopeKey(from: sharedSecret, format: format)
|
||||
return try XChaCha20Poly1305Compat.open(
|
||||
ciphertext: Data(ct),
|
||||
ciphertext: Data(ciphertextBytes),
|
||||
tag: Data(tag),
|
||||
key: key,
|
||||
nonce24: Data(nonce24)
|
||||
)
|
||||
}
|
||||
|
||||
// If 32 bytes (x-only) try both parities, otherwise single try
|
||||
let plaintext: Data
|
||||
if senderPubkeyData.count == 32 {
|
||||
let even = Data([0x02]) + senderPubkeyData
|
||||
if let pt = try? attemptDecrypt(using: even) {
|
||||
plaintext = pt
|
||||
let evenKey = Data([0x02]) + senderPubkeyData
|
||||
if let opened = try? attemptDecrypt(using: evenKey) {
|
||||
plaintext = opened
|
||||
} else {
|
||||
let odd = Data([0x03]) + senderPubkeyData
|
||||
plaintext = try attemptDecrypt(using: odd)
|
||||
let oddKey = Data([0x03]) + senderPubkeyData
|
||||
plaintext = try attemptDecrypt(using: oddKey)
|
||||
}
|
||||
} else {
|
||||
plaintext = try attemptDecrypt(using: senderPubkeyData)
|
||||
}
|
||||
|
||||
// Authenticated plaintext that is not valid UTF-8 is a malformed
|
||||
// envelope, not an empty message.
|
||||
guard let decoded = String(data: plaintext, encoding: .utf8) else {
|
||||
guard plaintext.count <= maximumPlaintextBytes,
|
||||
let decoded = String(data: plaintext, encoding: .utf8) else {
|
||||
throw NostrError.invalidCiphertext
|
||||
}
|
||||
return decoded
|
||||
@@ -740,30 +867,17 @@ struct NostrProtocol {
|
||||
let sharedSecretData = sharedSecret.withUnsafeBytes { Data($0) }
|
||||
// ECDH shared secret derived
|
||||
|
||||
// Return raw ECDH shared secret; HKDF is applied by
|
||||
// derivePrivateEnvelopeKey
|
||||
// Return raw ECDH shared secret; the wire-format-specific HKDF is
|
||||
// applied by derivePrivateEnvelopeKey.
|
||||
return sharedSecretData
|
||||
}
|
||||
|
||||
private static func randomizedTimestamp() -> Date {
|
||||
// Add random offset to current time for privacy
|
||||
// This prevents timing correlation attacks while the actual message timestamp
|
||||
// is preserved in the encrypted rumor
|
||||
let offset = TimeInterval.random(in: -900...900) // +/- 15 minutes
|
||||
let now = Date()
|
||||
let randomized = now.addingTimeInterval(offset)
|
||||
|
||||
// Log with explicit UTC and local time for debugging
|
||||
let formatter = DateFormatter()
|
||||
//
|
||||
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
|
||||
formatter.timeZone = TimeZone(abbreviation: "UTC")
|
||||
|
||||
formatter.timeZone = TimeZone.current
|
||||
|
||||
// Timestamp randomized for privacy
|
||||
|
||||
return randomized
|
||||
private static func randomizedPastTimestamp() -> Date {
|
||||
// Keep public timestamps in the past: future-dated events are rejected
|
||||
// by some relays. The actual message timestamp remains encrypted.
|
||||
Date().addingTimeInterval(
|
||||
-TimeInterval.random(in: 0...TransportConfig.nostrPrivateEnvelopeTimestampFuzzSeconds)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -901,15 +1015,14 @@ enum NostrError: Error {
|
||||
// MARK: - BitChat private-envelope key derivation
|
||||
|
||||
private extension NostrProtocol {
|
||||
/// The HKDF info string retains the historical "nip44-v2" label for wire
|
||||
/// compatibility with deployed clients, but this is not the NIP-44 key
|
||||
/// schedule: NIP-44 derives a conversation key via HKDF-extract with that
|
||||
/// label as the *salt* and uses ChaCha20 with per-message expanded keys.
|
||||
static func derivePrivateEnvelopeKey(from sharedSecretData: Data) throws -> Data {
|
||||
private static func derivePrivateEnvelopeKey(
|
||||
from sharedSecretData: Data,
|
||||
format: PrivateEnvelopeWireFormat
|
||||
) -> Data {
|
||||
let derivedKey = HKDF<CryptoKit.SHA256>.deriveKey(
|
||||
inputKeyMaterial: SymmetricKey(data: sharedSecretData),
|
||||
salt: Data(),
|
||||
info: Data("nip44-v2".utf8),
|
||||
salt: format.hkdfSalt,
|
||||
info: format.hkdfInfo,
|
||||
outputByteCount: 32
|
||||
)
|
||||
return derivedKey.withUnsafeBytes { Data($0) }
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,92 +0,0 @@
|
||||
//
|
||||
// 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,15 +38,11 @@
|
||||
/// 7. **Decoding**: Binary data parsed back to message objects
|
||||
///
|
||||
/// ## Security Considerations
|
||||
/// - 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
|
||||
/// - Message padding (to 256/512/1024/2048-byte blocks) obscures actual content length
|
||||
/// - 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
|
||||
/// - 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.
|
||||
/// - No persistent identifiers in protocol headers
|
||||
///
|
||||
/// ## Message Types
|
||||
/// - **Announce/Leave**: Peer presence notifications
|
||||
|
||||
@@ -114,9 +114,6 @@ 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 =
|
||||
@@ -572,84 +569,6 @@ 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)
|
||||
|
||||
@@ -2574,12 +2574,6 @@ final class BLEService: NSObject {
|
||||
gossipSyncManager?.removePublicMessages(from: peerID)
|
||||
}
|
||||
|
||||
/// Clearing the mesh timeline erases the archive behind it, so the cleared
|
||||
/// history is gone from disk rather than merely hidden from the timeline.
|
||||
func purgeAllArchivedPublicMessages() {
|
||||
gossipSyncManager?.removeAllPublicMessages()
|
||||
}
|
||||
|
||||
func collectArchivedPublicMessages(completion: @escaping @MainActor ([ArchivedPublicMessage]) -> Void) {
|
||||
guard let generation = capturePanicLifecycleGeneration() else {
|
||||
return
|
||||
|
||||
@@ -110,10 +110,6 @@ 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
|
||||
@@ -199,7 +195,7 @@ final class MessageOutboxStore {
|
||||
? (pendingSnapshot ?? [:])
|
||||
: Self.merge(durable, pendingSnapshot ?? [:]))
|
||||
diskState = .loaded
|
||||
if pendingSnapshot != nil || hasPendingRemovalsLocked {
|
||||
if pendingSnapshot != nil || !pendingRemovalMessageIDs.isEmpty {
|
||||
if persistSnapshotAndClearRemovalsLocked(cachedSnapshot) {
|
||||
pendingSnapshot = nil
|
||||
pendingSnapshotIsAuthoritative = false
|
||||
@@ -216,7 +212,7 @@ final class MessageOutboxStore {
|
||||
case .missing:
|
||||
cachedSnapshot = applyingPendingRemovalsLocked(pendingSnapshot ?? [:])
|
||||
diskState = .loaded
|
||||
if pendingSnapshot != nil || hasPendingRemovalsLocked {
|
||||
if pendingSnapshot != nil || !pendingRemovalMessageIDs.isEmpty {
|
||||
if persistSnapshotAndClearRemovalsLocked(cachedSnapshot) {
|
||||
pendingSnapshot = nil
|
||||
pendingSnapshotIsAuthoritative = false
|
||||
@@ -239,7 +235,7 @@ final class MessageOutboxStore {
|
||||
diskState = .loaded
|
||||
cachedSnapshot = applyingPendingRemovalsLocked(pendingSnapshot ?? [:])
|
||||
SecureLogger.error("Failed to decode encrypted outbox: \(error)", category: .session)
|
||||
if pendingSnapshot != nil || hasPendingRemovalsLocked {
|
||||
if pendingSnapshot != nil || !pendingRemovalMessageIDs.isEmpty {
|
||||
if persistSnapshotAndClearRemovalsLocked(cachedSnapshot) {
|
||||
pendingSnapshot = nil
|
||||
pendingSnapshotIsAuthoritative = false
|
||||
@@ -446,25 +442,6 @@ 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
|
||||
@@ -501,7 +478,7 @@ final class MessageOutboxStore {
|
||||
: (pendingSnapshotIsAuthoritative ? known : Self.merge(durable, known)))
|
||||
cachedSnapshot = merged
|
||||
diskState = .loaded
|
||||
if (pendingSnapshot == nil && !hasPendingRemovalsLocked) ||
|
||||
if (pendingSnapshot == nil && pendingRemovalMessageIDs.isEmpty) ||
|
||||
persistSnapshotAndClearRemovalsLocked(merged) {
|
||||
pendingSnapshot = nil
|
||||
pendingSnapshotIsAuthoritative = false
|
||||
@@ -530,7 +507,7 @@ final class MessageOutboxStore {
|
||||
: known)
|
||||
cachedSnapshot = merged
|
||||
diskState = .loaded
|
||||
if (pendingSnapshot == nil && !hasPendingRemovalsLocked) ||
|
||||
if (pendingSnapshot == nil && pendingRemovalMessageIDs.isEmpty) ||
|
||||
persistSnapshotAndClearRemovalsLocked(merged) {
|
||||
pendingSnapshot = nil
|
||||
pendingSnapshotIsAuthoritative = false
|
||||
@@ -562,7 +539,7 @@ final class MessageOutboxStore {
|
||||
: known)
|
||||
cachedSnapshot = merged
|
||||
diskState = .loaded
|
||||
if (pendingSnapshot == nil && !hasPendingRemovalsLocked) ||
|
||||
if (pendingSnapshot == nil && pendingRemovalMessageIDs.isEmpty) ||
|
||||
persistSnapshotAndClearRemovalsLocked(merged) {
|
||||
pendingSnapshot = nil
|
||||
pendingSnapshotIsAuthoritative = false
|
||||
@@ -601,7 +578,6 @@ final class MessageOutboxStore {
|
||||
pendingSnapshot = nil
|
||||
pendingSnapshotIsAuthoritative = false
|
||||
pendingRemovalMessageIDs.removeAll()
|
||||
pendingScopedRemovalMessageIDs.removeAll()
|
||||
recoveryDeliveryPending = false
|
||||
unseenRecoveryPendingPersistence = false
|
||||
unseenRecoveredSnapshot = [:]
|
||||
@@ -766,21 +742,12 @@ 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(
|
||||
pendingScopedRemovalMessageIDs,
|
||||
from: Self.removing(pendingRemovalMessageIDs, from: snapshot)
|
||||
)
|
||||
}
|
||||
|
||||
/// Must be read with `lock` held.
|
||||
private var hasPendingRemovalsLocked: Bool {
|
||||
!pendingRemovalMessageIDs.isEmpty || !pendingScopedRemovalMessageIDs.isEmpty
|
||||
Self.removing(pendingRemovalMessageIDs, from: snapshot)
|
||||
}
|
||||
|
||||
private static func removing(_ messageIDs: Set<String>, from snapshot: Snapshot) -> Snapshot {
|
||||
@@ -793,28 +760,9 @@ 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 {
|
||||
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
|
||||
let knownIDs = Set(known.values.flatMap { $0.map(\.messageID) })
|
||||
return removing(knownIDs, from: durable)
|
||||
}
|
||||
|
||||
private static func merge(_ durable: Snapshot, _ pending: Snapshot) -> Snapshot {
|
||||
|
||||
@@ -106,14 +106,13 @@ final class BridgeCourierService: ObservableObject {
|
||||
dedupKey: String?,
|
||||
operationID: UUID?
|
||||
)] = []
|
||||
/// 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.
|
||||
/// 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.
|
||||
private var publishedDropKeys: ExpiringIDSet
|
||||
private var seenDropEventIDs: ExpiringIDSet
|
||||
private var subscriptionOpen = false
|
||||
@@ -127,7 +126,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 recipient/message pair.
|
||||
/// a newer attempt for the same message.
|
||||
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
|
||||
@@ -215,46 +214,11 @@ 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 recipient/message pair. Completion becomes
|
||||
/// true only after a real relay acceptance arrives, which is when the
|
||||
/// router may show "carried".
|
||||
/// deposits; idempotent per message ID. Completion becomes true only
|
||||
/// after a real relay acceptance arrives, which is when the router may
|
||||
/// show "carried".
|
||||
func depositDrop(
|
||||
content: String,
|
||||
messageID: String,
|
||||
@@ -265,18 +229,9 @@ final class BridgeCourierService: ObservableObject {
|
||||
completion(false)
|
||||
return
|
||||
}
|
||||
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 {
|
||||
guard !publishedDropKeys.contains(messageID, now: now()),
|
||||
activeDropOperations[messageID] == nil,
|
||||
!rejectedDropKeys.contains(messageID, now: now()) else {
|
||||
completion(false)
|
||||
return
|
||||
}
|
||||
@@ -289,13 +244,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(dedupKey, now: date)
|
||||
rejectedDropKeys.insert(messageID, now: now())
|
||||
completion(false)
|
||||
return
|
||||
}
|
||||
let operationID = UUID()
|
||||
activeDropOperations[dedupKey] = ActiveDropOperation(id: operationID, completion: completion)
|
||||
publishDrop(envelope, dedupKey: dedupKey, operationID: operationID)
|
||||
activeDropOperations[messageID] = ActiveDropOperation(id: operationID, completion: completion)
|
||||
publishDrop(envelope, messageID: messageID, operationID: operationID)
|
||||
}
|
||||
|
||||
/// Publishes held envelopes (mail we carry for others) as drops,
|
||||
@@ -317,14 +272,13 @@ final class BridgeCourierService: ObservableObject {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
/// 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.
|
||||
private func publishDrop(
|
||||
_ envelope: CourierEnvelope,
|
||||
dedupKey: String? = nil,
|
||||
messageID: String? = nil,
|
||||
operationID: UUID? = nil,
|
||||
untrackedCompletion: (@MainActor (Bool) -> Void)? = nil
|
||||
) {
|
||||
@@ -332,7 +286,7 @@ final class BridgeCourierService: ObservableObject {
|
||||
encoded.count <= Limits.maxDropEnvelopeBytes,
|
||||
!envelope.isExpired else {
|
||||
finishPublish(
|
||||
dedupKey: dedupKey,
|
||||
messageID: messageID,
|
||||
operationID: operationID,
|
||||
succeeded: false,
|
||||
untrackedCompletion: untrackedCompletion
|
||||
@@ -343,15 +297,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 dedupKey != nil else {
|
||||
guard messageID != nil else {
|
||||
untrackedCompletion?(false)
|
||||
return
|
||||
}
|
||||
pendingDrops.append((envelope, dedupKey, operationID))
|
||||
pendingDrops.append((envelope, messageID, operationID))
|
||||
while pendingDrops.count > Limits.maxPendingDrops {
|
||||
let evicted = pendingDrops.removeFirst()
|
||||
finishPublish(
|
||||
dedupKey: evicted.dedupKey,
|
||||
messageID: evicted.dedupKey,
|
||||
operationID: evicted.operationID,
|
||||
succeeded: false
|
||||
)
|
||||
@@ -367,7 +321,7 @@ final class BridgeCourierService: ObservableObject {
|
||||
) else {
|
||||
SecureLogger.error("📦🌉 Failed to compose courier drop", category: .encryption)
|
||||
finishPublish(
|
||||
dedupKey: dedupKey,
|
||||
messageID: messageID,
|
||||
operationID: operationID,
|
||||
succeeded: false,
|
||||
untrackedCompletion: untrackedCompletion
|
||||
@@ -377,7 +331,7 @@ final class BridgeCourierService: ObservableObject {
|
||||
guard let publishEvent else {
|
||||
SecureLogger.error("📦🌉 Courier drop publisher is not configured", category: .session)
|
||||
finishPublish(
|
||||
dedupKey: dedupKey,
|
||||
messageID: messageID,
|
||||
operationID: operationID,
|
||||
succeeded: false,
|
||||
untrackedCompletion: untrackedCompletion
|
||||
@@ -387,7 +341,7 @@ final class BridgeCourierService: ObservableObject {
|
||||
publishEvent(event) { [weak self] succeeded in
|
||||
guard let self else { return }
|
||||
guard self.finishPublish(
|
||||
dedupKey: dedupKey,
|
||||
messageID: messageID,
|
||||
operationID: operationID,
|
||||
succeeded: succeeded,
|
||||
untrackedCompletion: untrackedCompletion
|
||||
@@ -402,23 +356,23 @@ final class BridgeCourierService: ObservableObject {
|
||||
|
||||
@discardableResult
|
||||
private func finishPublish(
|
||||
dedupKey: String?,
|
||||
messageID: String?,
|
||||
operationID: UUID?,
|
||||
succeeded: Bool,
|
||||
untrackedCompletion: (@MainActor (Bool) -> Void)? = nil
|
||||
) -> Bool {
|
||||
guard let dedupKey else {
|
||||
guard let messageID 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[dedupKey],
|
||||
let operation = activeDropOperations[messageID],
|
||||
operation.id == operationID else { return false }
|
||||
activeDropOperations.removeValue(forKey: dedupKey)
|
||||
activeDropOperations.removeValue(forKey: messageID)
|
||||
if succeeded {
|
||||
publishedDropKeys.insert(dedupKey, now: now())
|
||||
publishedDropKeys.insert(messageID, now: now())
|
||||
persistDedup()
|
||||
}
|
||||
operation.completion(succeeded)
|
||||
@@ -433,7 +387,7 @@ final class BridgeCourierService: ObservableObject {
|
||||
for item in queued {
|
||||
publishDrop(
|
||||
item.envelope,
|
||||
dedupKey: item.dedupKey,
|
||||
messageID: 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
|
||||
/// recipient/message pair per 24h regardless of relaunch count.
|
||||
/// device freeze. Persisting both sides caps this at one drop per message
|
||||
/// ID per 24h regardless of relaunch count.
|
||||
///
|
||||
/// Contents are opaque hashes and relay event IDs — no plaintext or peer
|
||||
/// identities — so until-first-unlock protection matches
|
||||
/// Contents are opaque IDs (message UUIDs, relay event IDs) — no plaintext,
|
||||
/// no 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,12 +10,9 @@ 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.
|
||||
///
|
||||
/// 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.
|
||||
/// 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.
|
||||
enum MeshEchoSettings {
|
||||
private static let clearedThroughKey = "meshEchoes.clearedThrough"
|
||||
|
||||
|
||||
@@ -34,15 +34,6 @@ 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
|
||||
@@ -113,25 +104,15 @@ final class MessageRouter {
|
||||
}
|
||||
|
||||
private var bridgeSweepTask: Task<Void, Never>?
|
||||
private var bridgeDepositsInFlight = Set<PeerMessageKey>()
|
||||
private var bridgeDepositsInFlight = Set<String>()
|
||||
|
||||
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 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.
|
||||
// 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).
|
||||
private static let maxSendAttempts = 8
|
||||
// Redundant couriers improve delivery odds; receivers dedup by message ID.
|
||||
private static let maxCouriersPerMessage = 3
|
||||
@@ -177,6 +158,16 @@ final class MessageRouter {
|
||||
}
|
||||
}
|
||||
|
||||
/// Wire one typed event sink to every route, including the queue-backed
|
||||
/// Nostr transport. Keeping this at the router boundary prevents a relay
|
||||
/// admission failure from disappearing merely because only the primary
|
||||
/// mesh transport was assigned a UI delegate.
|
||||
func setEventDelegate(_ delegate: TransportEventDelegate?) {
|
||||
for transport in transports {
|
||||
transport.eventDelegate = delegate
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Transport Selection
|
||||
|
||||
private func reachableTransport(for peerID: PeerID) -> Transport? {
|
||||
@@ -190,28 +181,15 @@ 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) {
|
||||
// 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))
|
||||
// A live link that can complete an encrypted delivery is a
|
||||
// strong delivery signal; trust it outright.
|
||||
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
|
||||
@@ -229,9 +207,8 @@ 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)
|
||||
enqueue(message, for: peerID)
|
||||
secureTransmissions.remove(PeerMessageKey(peerID: peerID, messageID: messageID))
|
||||
transport.sendPrivateMessage(content, to: peerID, recipientNickname: recipientNickname, messageID: messageID)
|
||||
enqueue(message, for: peerID)
|
||||
attemptCourierDeposit(messageID: messageID, for: peerID)
|
||||
return
|
||||
}
|
||||
@@ -242,8 +219,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)
|
||||
enqueue(message, for: peerID)
|
||||
transport.sendPrivateMessage(content, to: peerID, recipientNickname: recipientNickname, messageID: messageID)
|
||||
enqueue(message, for: peerID)
|
||||
// "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
|
||||
@@ -366,12 +343,11 @@ final class MessageRouter {
|
||||
for peerID: PeerID,
|
||||
recipientKey: Data
|
||||
) {
|
||||
let inFlightKey = PeerMessageKey(peerID: peerID, messageID: message.messageID)
|
||||
guard let bridgeCourierDeposit,
|
||||
bridgeDepositsInFlight.insert(inFlightKey).inserted else { return }
|
||||
bridgeDepositsInFlight.insert(message.messageID).inserted else { return }
|
||||
bridgeCourierDeposit(message.content, message.messageID, recipientKey) { [weak self] succeeded in
|
||||
guard let self else { return }
|
||||
self.bridgeDepositsInFlight.remove(inFlightKey)
|
||||
self.bridgeDepositsInFlight.remove(message.messageID)
|
||||
// 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 }
|
||||
@@ -390,23 +366,8 @@ final class MessageRouter {
|
||||
|
||||
// MARK: - Outbox Management
|
||||
|
||||
/// 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.
|
||||
/// A delivery or read ack confirms receipt; stop retaining the message.
|
||||
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 }
|
||||
@@ -414,10 +375,6 @@ 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.
|
||||
@@ -428,35 +385,6 @@ 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] ?? []
|
||||
@@ -480,34 +408,7 @@ 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)
|
||||
}
|
||||
@@ -551,7 +452,6 @@ final class MessageRouter {
|
||||
/// Panic wipe: forget queued mail on disk and in memory.
|
||||
func wipeOutbox() {
|
||||
outbox.removeAll()
|
||||
secureTransmissions.removeAll()
|
||||
outboxStore?.wipe()
|
||||
}
|
||||
|
||||
@@ -579,160 +479,26 @@ 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 outboxChanged = false
|
||||
var remaining: [QueuedMessage] = []
|
||||
|
||||
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)
|
||||
if removeQueuedMessage(message.messageID, for: peerID) {
|
||||
dropMessage(message.messageID, for: peerID)
|
||||
outboxChanged = true
|
||||
}
|
||||
dropMessage(message.messageID, for: peerID)
|
||||
continue
|
||||
}
|
||||
|
||||
if let transport = connectedTransport(for: peerID), transport.canDeliverSecurely(to: peerID) {
|
||||
// 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
|
||||
}
|
||||
// Live link with a secure session: send and stop retaining.
|
||||
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
|
||||
@@ -745,11 +511,9 @@ 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
|
||||
@@ -757,22 +521,26 @@ 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)
|
||||
if removeQueuedMessage(message.messageID, for: peerID) {
|
||||
dropMessage(message.messageID, for: peerID)
|
||||
outboxChanged = true
|
||||
}
|
||||
dropMessage(message.messageID, for: peerID)
|
||||
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)
|
||||
outboxChanged = incrementSendAttemptsIfQueued(message.messageID, for: peerID) || outboxChanged
|
||||
var retained = message
|
||||
retained.sendAttempts += 1
|
||||
remaining.append(retained)
|
||||
} else {
|
||||
remaining.append(message)
|
||||
}
|
||||
}
|
||||
|
||||
if outboxChanged {
|
||||
persistOutbox()
|
||||
if remaining.isEmpty {
|
||||
outbox.removeValue(forKey: peerID)
|
||||
} else {
|
||||
outbox[peerID] = remaining
|
||||
}
|
||||
persistOutbox()
|
||||
}
|
||||
|
||||
func flushAllOutbox() {
|
||||
|
||||
@@ -42,18 +42,13 @@ final class NetworkActivationService: ObservableObject {
|
||||
|
||||
private var cancellables = Set<AnyCancellable>()
|
||||
private var started = false
|
||||
/// 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 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
|
||||
@@ -68,13 +63,8 @@ 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 }
|
||||
@@ -88,8 +78,6 @@ 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,
|
||||
@@ -101,8 +89,6 @@ 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 }
|
||||
@@ -110,25 +96,11 @@ 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: Self.torPreferenceKey) as? Bool {
|
||||
if let stored = storage.object(forKey: torPreferenceKey) as? Bool {
|
||||
userTorEnabled = stored
|
||||
} else {
|
||||
userTorEnabled = true
|
||||
@@ -166,16 +138,6 @@ 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)
|
||||
@@ -208,7 +170,7 @@ final class NetworkActivationService: ObservableObject {
|
||||
func setUserTorEnabled(_ enabled: Bool) {
|
||||
guard enabled != userTorEnabled else { return }
|
||||
userTorEnabled = enabled
|
||||
storage.set(enabled, forKey: Self.torPreferenceKey)
|
||||
storage.set(enabled, forKey: torPreferenceKey)
|
||||
notificationCenter.post(
|
||||
name: .TorUserPreferenceChanged,
|
||||
object: nil,
|
||||
@@ -249,14 +211,7 @@ final class NetworkActivationService: ObservableObject {
|
||||
private func basePolicyAllowed() -> Bool {
|
||||
let permOK = permissionProvider() == .authorized
|
||||
let hasMutual = !mutualFavoritesProvider().isEmpty
|
||||
// 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
|
||||
return permOK || hasMutual
|
||||
}
|
||||
|
||||
/// 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.
|
||||
|
||||
@@ -11,8 +11,12 @@ final class NostrTransport: Transport, @unchecked Sendable {
|
||||
let favoriteStatusForNoiseKey: @MainActor (Data) -> FavoritesPersistenceService.FavoriteRelationship?
|
||||
let favoriteStatusForPeerID: @MainActor (PeerID) -> FavoritesPersistenceService.FavoriteRelationship?
|
||||
let currentIdentity: @MainActor () throws -> NostrIdentity?
|
||||
let registerPendingGiftWrap: @MainActor (String) -> Void
|
||||
let sendEvent: @MainActor (NostrEvent) -> Void
|
||||
let registerPendingPrivateEnvelope: @MainActor (String) -> Void
|
||||
let sendPrivateEnvelopeBatch: @MainActor (
|
||||
[NostrEvent],
|
||||
@escaping @MainActor () -> Void
|
||||
) -> Bool
|
||||
let envelopeRetryQueue: NostrPrivateEnvelopeRetryQueue
|
||||
/// Emits whether a relay that carries private messages is up
|
||||
/// (fail-closed behind Tor). A connected geohash/custom relay alone
|
||||
/// doesn't count: DM sends target the default relay set and would
|
||||
@@ -22,25 +26,35 @@ final class NostrTransport: Transport, @unchecked Sendable {
|
||||
/// serialize behind each other; `live` passes the process-wide one.
|
||||
let ackPacer: AckPacer
|
||||
|
||||
@MainActor
|
||||
init(
|
||||
notificationCenter: NotificationCenter,
|
||||
loadFavorites: @escaping @MainActor () -> [Data: FavoritesPersistenceService.FavoriteRelationship],
|
||||
favoriteStatusForNoiseKey: @escaping @MainActor (Data) -> FavoritesPersistenceService.FavoriteRelationship?,
|
||||
favoriteStatusForPeerID: @escaping @MainActor (PeerID) -> FavoritesPersistenceService.FavoriteRelationship?,
|
||||
currentIdentity: @escaping @MainActor () throws -> NostrIdentity?,
|
||||
registerPendingGiftWrap: @escaping @MainActor (String) -> Void,
|
||||
sendEvent: @escaping @MainActor (NostrEvent) -> Void,
|
||||
registerPendingPrivateEnvelope: @escaping @MainActor (String) -> Void,
|
||||
sendPrivateEnvelopeBatch: @escaping @MainActor (
|
||||
[NostrEvent],
|
||||
@escaping @MainActor () -> Void
|
||||
) -> Bool,
|
||||
scheduleAfter: @escaping @Sendable (TimeInterval, @escaping @Sendable () -> Void) -> Void,
|
||||
relayConnectivity: @escaping @MainActor () -> AnyPublisher<Bool, Never>,
|
||||
ackPacer: AckPacer? = nil
|
||||
ackPacer: AckPacer? = nil,
|
||||
envelopeRetryQueue: NostrPrivateEnvelopeRetryQueue? = nil
|
||||
) {
|
||||
self.notificationCenter = notificationCenter
|
||||
self.loadFavorites = loadFavorites
|
||||
self.favoriteStatusForNoiseKey = favoriteStatusForNoiseKey
|
||||
self.favoriteStatusForPeerID = favoriteStatusForPeerID
|
||||
self.currentIdentity = currentIdentity
|
||||
self.registerPendingGiftWrap = registerPendingGiftWrap
|
||||
self.sendEvent = sendEvent
|
||||
self.registerPendingPrivateEnvelope = registerPendingPrivateEnvelope
|
||||
self.sendPrivateEnvelopeBatch = sendPrivateEnvelopeBatch
|
||||
self.envelopeRetryQueue = envelopeRetryQueue ?? NostrPrivateEnvelopeRetryQueue(
|
||||
sendPrivateEnvelopeBatch: sendPrivateEnvelopeBatch,
|
||||
registerPendingPrivateEnvelope: registerPendingPrivateEnvelope,
|
||||
scheduleAfter: scheduleAfter
|
||||
)
|
||||
self.relayConnectivity = relayConnectivity
|
||||
// Default pacer drives its throttle through the same injected
|
||||
// scheduler, so tests that step scheduleAfter manually keep
|
||||
@@ -56,13 +70,19 @@ final class NostrTransport: Transport, @unchecked Sendable {
|
||||
favoriteStatusForNoiseKey: { FavoritesPersistenceService.shared.getFavoriteStatus(for: $0) },
|
||||
favoriteStatusForPeerID: { FavoritesPersistenceService.shared.getFavoriteStatus(forPeerID: $0) },
|
||||
currentIdentity: { try idBridge.getCurrentNostrIdentity() },
|
||||
registerPendingGiftWrap: { NostrRelayManager.registerPendingGiftWrap(id: $0) },
|
||||
sendEvent: { NostrRelayManager.shared.sendEvent($0) },
|
||||
registerPendingPrivateEnvelope: { NostrRelayManager.registerPendingPrivateEnvelope(id: $0) },
|
||||
sendPrivateEnvelopeBatch: { events, terminalFailure in
|
||||
NostrRelayManager.shared.sendPrivateEnvelopeBatch(
|
||||
events,
|
||||
terminalFailure: terminalFailure
|
||||
)
|
||||
},
|
||||
scheduleAfter: { delay, action in
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: action)
|
||||
},
|
||||
relayConnectivity: { NostrRelayManager.shared.$isDMRelayConnected.eraseToAnyPublisher() },
|
||||
ackPacer: NostrTransport.sharedAckPacer
|
||||
ackPacer: NostrTransport.sharedAckPacer,
|
||||
envelopeRetryQueue: NostrTransport.sharedEnvelopeRetryQueue
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -128,7 +148,37 @@ final class NostrTransport: Transport, @unchecked Sendable {
|
||||
}
|
||||
}
|
||||
static let sharedAckPacer = AckPacer()
|
||||
// Geohash acknowledgements use short-lived NostrTransport instances, so
|
||||
// the retry owner must be process-wide. A per-transport cap would still be
|
||||
// globally unbounded under outage as throwaway instances accumulated.
|
||||
@MainActor
|
||||
private static let sharedEnvelopeRetryQueue = NostrPrivateEnvelopeRetryQueue(
|
||||
sendPrivateEnvelopeBatch: { events, terminalFailure in
|
||||
NostrRelayManager.shared.sendPrivateEnvelopeBatch(
|
||||
events,
|
||||
terminalFailure: terminalFailure
|
||||
)
|
||||
},
|
||||
registerPendingPrivateEnvelope: {
|
||||
NostrRelayManager.registerPendingPrivateEnvelope(id: $0)
|
||||
},
|
||||
scheduleAfter: { delay, action in
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: action)
|
||||
}
|
||||
)
|
||||
|
||||
@MainActor
|
||||
static func resetControlRetriesForPanicWipe() {
|
||||
sharedEnvelopeRetryQueue.removeAll()
|
||||
}
|
||||
|
||||
private enum PrivateEnvelopeFailurePolicy {
|
||||
case userMessage(messageID: String)
|
||||
case retry(retryKey: String)
|
||||
}
|
||||
|
||||
private let dependencies: Dependencies
|
||||
private let envelopeRetryQueue: NostrPrivateEnvelopeRetryQueue
|
||||
private var favoriteStatusObserver: NSObjectProtocol?
|
||||
|
||||
// Reachability Cache (thread-safe)
|
||||
@@ -145,7 +195,9 @@ final class NostrTransport: Transport, @unchecked Sendable {
|
||||
idBridge: NostrIdentityBridge,
|
||||
dependencies: Dependencies? = nil
|
||||
) {
|
||||
self.dependencies = dependencies ?? .live(idBridge: idBridge)
|
||||
let resolvedDependencies = dependencies ?? .live(idBridge: idBridge)
|
||||
self.dependencies = resolvedDependencies
|
||||
self.envelopeRetryQueue = resolvedDependencies.envelopeRetryQueue
|
||||
|
||||
setupObservers()
|
||||
|
||||
@@ -172,6 +224,18 @@ final class NostrTransport: Transport, @unchecked Sendable {
|
||||
}
|
||||
}
|
||||
|
||||
#if DEBUG
|
||||
@MainActor
|
||||
func debugEnqueueControlRetry(key: String, events: [NostrEvent]) {
|
||||
envelopeRetryQueue.enqueue(key: key, events: events, registerPending: false)
|
||||
}
|
||||
|
||||
@MainActor
|
||||
var debugControlRetryCount: Int {
|
||||
envelopeRetryQueue.debugPendingCount
|
||||
}
|
||||
#endif
|
||||
|
||||
private func setupObservers() {
|
||||
favoriteStatusObserver = dependencies.notificationCenter.addObserver(
|
||||
forName: .favoriteStatusChanged,
|
||||
@@ -253,15 +317,49 @@ final class NostrTransport: Transport, @unchecked Sendable {
|
||||
|
||||
func sendPrivateMessage(_ content: String, to peerID: PeerID, recipientNickname: String, messageID: String) {
|
||||
Task { @MainActor in
|
||||
guard let recipientNpub = resolveRecipientNpub(for: peerID),
|
||||
let recipientHex = npubToHex(recipientNpub),
|
||||
let senderIdentity = try? dependencies.currentIdentity() else { return }
|
||||
let failurePolicy = PrivateEnvelopeFailurePolicy.userMessage(
|
||||
messageID: messageID
|
||||
)
|
||||
guard let recipientNpub = resolveRecipientNpub(for: peerID) else {
|
||||
handlePrivateEnvelopeFailure(
|
||||
events: [],
|
||||
registerPending: false,
|
||||
policy: failurePolicy
|
||||
)
|
||||
return
|
||||
}
|
||||
guard let recipientHex = npubToHex(recipientNpub) else {
|
||||
handlePrivateEnvelopeFailure(
|
||||
events: [],
|
||||
registerPending: false,
|
||||
policy: failurePolicy
|
||||
)
|
||||
return
|
||||
}
|
||||
guard let senderIdentity = try? dependencies.currentIdentity() else {
|
||||
handlePrivateEnvelopeFailure(
|
||||
events: [],
|
||||
registerPending: false,
|
||||
policy: failurePolicy
|
||||
)
|
||||
return
|
||||
}
|
||||
SecureLogger.debug("NostrTransport: preparing PM to \(recipientNpub.prefix(16))… id=\(messageID.prefix(8))…", category: .session)
|
||||
guard let embedded = NostrEmbeddedBitChat.encodePMForNostr(content: content, messageID: messageID, recipientPeerID: peerID, senderPeerID: senderPeerID) else {
|
||||
SecureLogger.error("NostrTransport: failed to embed PM packet", category: .session)
|
||||
handlePrivateEnvelopeFailure(
|
||||
events: [],
|
||||
registerPending: false,
|
||||
policy: failurePolicy
|
||||
)
|
||||
return
|
||||
}
|
||||
sendWrappedMessage(content: embedded, recipientHex: recipientHex, senderIdentity: senderIdentity)
|
||||
sendPrivateEnvelope(
|
||||
content: embedded,
|
||||
recipientHex: recipientHex,
|
||||
senderIdentity: senderIdentity,
|
||||
failurePolicy: failurePolicy
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -287,7 +385,14 @@ final class NostrTransport: Transport, @unchecked Sendable {
|
||||
SecureLogger.error("NostrTransport: failed to embed favorite notification", category: .session)
|
||||
return
|
||||
}
|
||||
sendWrappedMessage(content: embedded, recipientHex: recipientHex, senderIdentity: senderIdentity)
|
||||
sendPrivateEnvelope(
|
||||
content: embedded,
|
||||
recipientHex: recipientHex,
|
||||
senderIdentity: senderIdentity,
|
||||
failurePolicy: .retry(
|
||||
retryKey: privateEnvelopeRetryKey(content: embedded, recipientHex: recipientHex)
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -311,16 +416,48 @@ extension NostrTransport {
|
||||
}
|
||||
|
||||
// MARK: Geohash DMs (per-geohash identity)
|
||||
func sendPrivateMessageGeohash(content: String, toRecipientHex recipientHex: String, from identity: NostrIdentity, messageID: String) {
|
||||
Task { @MainActor in
|
||||
guard !recipientHex.isEmpty else { return }
|
||||
SecureLogger.debug("GeoDM: send PM mid=\(messageID.prefix(8))…", category: .session)
|
||||
guard let embedded = NostrEmbeddedBitChat.encodePMForNostrNoRecipient(content: content, messageID: messageID, senderPeerID: senderPeerID) else {
|
||||
SecureLogger.error("NostrTransport: failed to embed geohash PM packet", category: .session)
|
||||
return
|
||||
}
|
||||
sendWrappedMessage(content: embedded, recipientHex: recipientHex, senderIdentity: identity, registerPending: true)
|
||||
/// Returns true only when the complete migration pair entered the relay
|
||||
/// delivery queue. GeoDM callers use this synchronous admission result
|
||||
/// before showing "sent"; deterministic packet/envelope failures must not
|
||||
/// be hidden behind an unobserved MainActor task.
|
||||
@MainActor
|
||||
@discardableResult
|
||||
func sendPrivateMessageGeohash(
|
||||
content: String,
|
||||
toRecipientHex recipientHex: String,
|
||||
from identity: NostrIdentity,
|
||||
messageID: String
|
||||
) -> Bool {
|
||||
let failurePolicy = PrivateEnvelopeFailurePolicy.userMessage(messageID: messageID)
|
||||
guard !recipientHex.isEmpty else {
|
||||
handlePrivateEnvelopeFailure(
|
||||
events: [],
|
||||
registerPending: false,
|
||||
policy: failurePolicy
|
||||
)
|
||||
return false
|
||||
}
|
||||
SecureLogger.debug("GeoDM: send PM mid=\(messageID.prefix(8))…", category: .session)
|
||||
guard let embedded = NostrEmbeddedBitChat.encodePMForNostrNoRecipient(
|
||||
content: content,
|
||||
messageID: messageID,
|
||||
senderPeerID: senderPeerID
|
||||
) else {
|
||||
SecureLogger.error("NostrTransport: failed to embed geohash PM packet", category: .session)
|
||||
handlePrivateEnvelopeFailure(
|
||||
events: [],
|
||||
registerPending: false,
|
||||
policy: failurePolicy
|
||||
)
|
||||
return false
|
||||
}
|
||||
return sendPrivateEnvelope(
|
||||
content: embedded,
|
||||
recipientHex: recipientHex,
|
||||
senderIdentity: identity,
|
||||
registerPending: true,
|
||||
failurePolicy: failurePolicy
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -340,17 +477,112 @@ extension NostrTransport {
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates and sends a gift-wrapped private message event
|
||||
/// Creates and sends a BitChat private-envelope event over Nostr.
|
||||
@MainActor
|
||||
private func sendWrappedMessage(content: String, recipientHex: String, senderIdentity: NostrIdentity, registerPending: Bool = false) {
|
||||
guard let event = try? NostrProtocol.createPrivateMessage(content: content, recipientPubkey: recipientHex, senderIdentity: senderIdentity) else {
|
||||
SecureLogger.error("NostrTransport: failed to build Nostr event", category: .session)
|
||||
return
|
||||
@discardableResult
|
||||
private func sendPrivateEnvelope(
|
||||
content: String,
|
||||
recipientHex: String,
|
||||
senderIdentity: NostrIdentity,
|
||||
registerPending: Bool = false,
|
||||
failurePolicy: PrivateEnvelopeFailurePolicy
|
||||
) -> Bool {
|
||||
let events: [NostrEvent]
|
||||
do {
|
||||
events = try NostrProtocol.createPrivateEnvelopePublicationBatch(
|
||||
content: content,
|
||||
recipientPubkey: recipientHex,
|
||||
senderIdentity: senderIdentity
|
||||
)
|
||||
} catch {
|
||||
SecureLogger.error(
|
||||
"NostrTransport: failed to build Nostr private-envelope batch: \(error)",
|
||||
category: .session
|
||||
)
|
||||
// Construction failures are deterministic. User-authored messages
|
||||
// must become visibly failed; control payloads have no valid event
|
||||
// pair to retain and retry.
|
||||
handlePrivateEnvelopeFailure(
|
||||
events: [],
|
||||
registerPending: false,
|
||||
policy: failurePolicy
|
||||
)
|
||||
return false
|
||||
}
|
||||
if registerPending {
|
||||
dependencies.registerPendingGiftWrap(event.id)
|
||||
let accepted = dependencies.sendPrivateEnvelopeBatch(events) { [self] in
|
||||
handlePrivateEnvelopeFailure(
|
||||
events: events,
|
||||
registerPending: registerPending,
|
||||
policy: failurePolicy
|
||||
)
|
||||
}
|
||||
guard accepted else {
|
||||
SecureLogger.error(
|
||||
"NostrTransport: private-envelope migration pair was not accepted for relay delivery",
|
||||
category: .session
|
||||
)
|
||||
handlePrivateEnvelopeFailure(
|
||||
events: events,
|
||||
registerPending: registerPending,
|
||||
policy: failurePolicy
|
||||
)
|
||||
return false
|
||||
}
|
||||
registerPendingPrivateEnvelopesIfNeeded(events, registerPending: registerPending)
|
||||
return true
|
||||
}
|
||||
|
||||
@MainActor
|
||||
private func handlePrivateEnvelopeFailure(
|
||||
events: [NostrEvent],
|
||||
registerPending: Bool,
|
||||
policy: PrivateEnvelopeFailurePolicy
|
||||
) {
|
||||
switch policy {
|
||||
case .userMessage(let messageID):
|
||||
deliverTransportEvent(.messageDeliveryStatusUpdated(
|
||||
messageID: messageID,
|
||||
status: .failed(reason: String(
|
||||
localized: "content.delivery.reason.not_delivered",
|
||||
comment: "Failure reason shown when a private message could not enter the relay delivery queue"
|
||||
))
|
||||
))
|
||||
case .retry(let retryKey):
|
||||
// A deterministic packet/envelope construction failure has no
|
||||
// events to retry. Only relay admission/delivery failures reach
|
||||
// this branch with the complete atomic pair.
|
||||
guard !events.isEmpty else { return }
|
||||
envelopeRetryQueue.enqueue(
|
||||
key: retryKey,
|
||||
events: events,
|
||||
registerPending: registerPending
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
private func registerPendingPrivateEnvelopesIfNeeded(
|
||||
_ events: [NostrEvent],
|
||||
registerPending: Bool
|
||||
) {
|
||||
guard registerPending else { return }
|
||||
for event in events {
|
||||
dependencies.registerPendingPrivateEnvelope(event.id)
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
private func privateEnvelopeRetryKey(content: String, recipientHex: String) -> String {
|
||||
"\(recipientHex.lowercased()):\(Data(content.utf8).sha256Fingerprint())"
|
||||
}
|
||||
|
||||
@MainActor
|
||||
private func deliverTransportEvent(_ event: TransportEvent) {
|
||||
if let eventDelegate {
|
||||
eventDelegate.didReceiveTransportEvent(event)
|
||||
} else {
|
||||
delegate?.receiveTransportEvent(event)
|
||||
}
|
||||
dependencies.sendEvent(event)
|
||||
}
|
||||
|
||||
|
||||
@@ -367,7 +599,14 @@ extension NostrTransport {
|
||||
SecureLogger.error("NostrTransport: failed to embed READ ack", category: .session)
|
||||
return
|
||||
}
|
||||
sendWrappedMessage(content: ack, recipientHex: recipientHex, senderIdentity: senderIdentity)
|
||||
sendPrivateEnvelope(
|
||||
content: ack,
|
||||
recipientHex: recipientHex,
|
||||
senderIdentity: senderIdentity,
|
||||
failurePolicy: .retry(
|
||||
retryKey: privateEnvelopeRetryKey(content: ack, recipientHex: recipientHex)
|
||||
)
|
||||
)
|
||||
|
||||
case .deliveredDirect(let messageID, let peerID):
|
||||
guard let recipientNpub = resolveRecipientNpub(for: peerID),
|
||||
@@ -378,17 +617,40 @@ extension NostrTransport {
|
||||
SecureLogger.error("NostrTransport: failed to embed DELIVERED ack", category: .session)
|
||||
return
|
||||
}
|
||||
sendWrappedMessage(content: ack, recipientHex: recipientHex, senderIdentity: senderIdentity)
|
||||
sendPrivateEnvelope(
|
||||
content: ack,
|
||||
recipientHex: recipientHex,
|
||||
senderIdentity: senderIdentity,
|
||||
failurePolicy: .retry(
|
||||
retryKey: privateEnvelopeRetryKey(content: ack, recipientHex: recipientHex)
|
||||
)
|
||||
)
|
||||
|
||||
case .deliveredGeohash(let messageID, let recipientHex, let identity):
|
||||
SecureLogger.debug("GeoDM: send DELIVERED mid=\(messageID.prefix(8))…", category: .session)
|
||||
guard let embedded = NostrEmbeddedBitChat.encodeAckForNostrNoRecipient(type: .delivered, messageID: messageID, senderPeerID: senderPeerID) else { return }
|
||||
sendWrappedMessage(content: embedded, recipientHex: recipientHex, senderIdentity: identity, registerPending: true)
|
||||
sendPrivateEnvelope(
|
||||
content: embedded,
|
||||
recipientHex: recipientHex,
|
||||
senderIdentity: identity,
|
||||
registerPending: true,
|
||||
failurePolicy: .retry(
|
||||
retryKey: privateEnvelopeRetryKey(content: embedded, recipientHex: recipientHex)
|
||||
)
|
||||
)
|
||||
|
||||
case .readGeohash(let messageID, let recipientHex, let identity):
|
||||
SecureLogger.debug("GeoDM: send READ mid=\(messageID.prefix(8))…", category: .session)
|
||||
guard let embedded = NostrEmbeddedBitChat.encodeAckForNostrNoRecipient(type: .readReceipt, messageID: messageID, senderPeerID: senderPeerID) else { return }
|
||||
sendWrappedMessage(content: embedded, recipientHex: recipientHex, senderIdentity: identity, registerPending: true)
|
||||
sendPrivateEnvelope(
|
||||
content: embedded,
|
||||
recipientHex: recipientHex,
|
||||
senderIdentity: identity,
|
||||
registerPending: true,
|
||||
failurePolicy: .retry(
|
||||
retryKey: privateEnvelopeRetryKey(content: embedded, recipientHex: recipientHex)
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -408,3 +670,122 @@ extension NostrTransport {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
/// Bounded retry owner for non-user private control payloads. It is separate
|
||||
/// from `NostrTransport` so a scheduled retry from a short-lived geohash
|
||||
/// transport remains valid after that transport deinitializes. Scheduler
|
||||
/// callbacks retain this queue, never the transport; an evicted key simply
|
||||
/// becomes a harmless no-op when its already-scheduled callback fires.
|
||||
@MainActor
|
||||
final class NostrPrivateEnvelopeRetryQueue {
|
||||
private struct PendingRetry {
|
||||
let events: [NostrEvent]
|
||||
let registerPending: Bool
|
||||
var attempt: Int
|
||||
var isScheduled: Bool
|
||||
}
|
||||
|
||||
private let sendPrivateEnvelopeBatch: @MainActor (
|
||||
[NostrEvent],
|
||||
@escaping @MainActor () -> Void
|
||||
) -> Bool
|
||||
private let registerPendingPrivateEnvelope: @MainActor (String) -> Void
|
||||
private let scheduleAfter: @Sendable (
|
||||
TimeInterval,
|
||||
@escaping @Sendable () -> Void
|
||||
) -> Void
|
||||
private var pending: [String: PendingRetry] = [:]
|
||||
private var insertionOrder: [String] = []
|
||||
|
||||
init(
|
||||
sendPrivateEnvelopeBatch: @escaping @MainActor (
|
||||
[NostrEvent],
|
||||
@escaping @MainActor () -> Void
|
||||
) -> Bool,
|
||||
registerPendingPrivateEnvelope: @escaping @MainActor (String) -> Void,
|
||||
scheduleAfter: @escaping @Sendable (
|
||||
TimeInterval,
|
||||
@escaping @Sendable () -> Void
|
||||
) -> Void
|
||||
) {
|
||||
self.sendPrivateEnvelopeBatch = sendPrivateEnvelopeBatch
|
||||
self.registerPendingPrivateEnvelope = registerPendingPrivateEnvelope
|
||||
self.scheduleAfter = scheduleAfter
|
||||
}
|
||||
|
||||
func enqueue(key: String, events: [NostrEvent], registerPending: Bool) {
|
||||
guard pending[key] == nil else { return }
|
||||
if pending.count >= TransportConfig.nostrPrivateEnvelopeRetryQueueCap,
|
||||
let evictedKey = insertionOrder.first {
|
||||
insertionOrder.removeFirst()
|
||||
pending.removeValue(forKey: evictedKey)
|
||||
// These are control payloads, never user-authored messages. Keep
|
||||
// the bounded-loss decision explicit rather than silently growing
|
||||
// memory during a prolonged outage.
|
||||
SecureLogger.warning(
|
||||
"📮 Private control retry queue full — evicted oldest whole migration pair",
|
||||
category: .session
|
||||
)
|
||||
}
|
||||
pending[key] = PendingRetry(
|
||||
events: events,
|
||||
registerPending: registerPending,
|
||||
attempt: 0,
|
||||
isScheduled: false
|
||||
)
|
||||
insertionOrder.append(key)
|
||||
schedule(key: key)
|
||||
}
|
||||
|
||||
private func schedule(key: String) {
|
||||
guard var item = pending[key], !item.isScheduled else { return }
|
||||
item.isScheduled = true
|
||||
pending[key] = item
|
||||
let exponent = min(item.attempt, 5)
|
||||
let delay = min(2.0 * pow(2.0, Double(exponent)), 60.0)
|
||||
scheduleAfter(delay) { [self] in
|
||||
Task { @MainActor [self] in
|
||||
self.retry(key: key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func retry(key: String) {
|
||||
guard var item = pending[key] else { return }
|
||||
item.isScheduled = false
|
||||
pending[key] = item
|
||||
|
||||
let accepted = sendPrivateEnvelopeBatch(item.events) { [self] in
|
||||
self.enqueue(
|
||||
key: key,
|
||||
events: item.events,
|
||||
registerPending: item.registerPending
|
||||
)
|
||||
}
|
||||
if accepted {
|
||||
remove(key: key)
|
||||
if item.registerPending {
|
||||
for event in item.events {
|
||||
registerPendingPrivateEnvelope(event.id)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
item.attempt += 1
|
||||
pending[key] = item
|
||||
schedule(key: key)
|
||||
}
|
||||
}
|
||||
|
||||
private func remove(key: String) {
|
||||
pending.removeValue(forKey: key)
|
||||
insertionOrder.removeAll { $0 == key }
|
||||
}
|
||||
|
||||
func removeAll() {
|
||||
pending.removeAll()
|
||||
insertionOrder.removeAll()
|
||||
}
|
||||
|
||||
var debugPendingCount: Int { pending.count }
|
||||
func debugContains(key: String) -> Bool { pending[key] != nil }
|
||||
}
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
//
|
||||
// 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,35 +95,6 @@ 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
|
||||
@@ -135,7 +106,6 @@ final class NotificationService {
|
||||
}
|
||||
|
||||
private init() {
|
||||
self.hidePreviewsProvider = { NotificationPrivacySettings.hideMessagePreviews }
|
||||
self.isRunningTestsProvider = {
|
||||
let env = ProcessInfo.processInfo.environment
|
||||
return NSClassFromString("XCTestCase") != nil ||
|
||||
@@ -160,14 +130,12 @@ final class NotificationService {
|
||||
isRunningTestsProvider: @escaping () -> Bool,
|
||||
authorizer: NotificationAuthorizing,
|
||||
requestDeliverer: NotificationRequestDelivering,
|
||||
categoryRegistrar: NotificationCategoryRegistering = NoopNotificationCategoryRegistrar(),
|
||||
hidePreviewsProvider: @escaping () -> Bool = { NotificationPrivacySettings.hideMessagePreviews }
|
||||
categoryRegistrar: NotificationCategoryRegistering = NoopNotificationCategoryRegistrar()
|
||||
) {
|
||||
self.isRunningTestsProvider = isRunningTestsProvider
|
||||
self.authorizer = authorizer
|
||||
self.requestDeliverer = requestDeliverer
|
||||
self.categoryRegistrar = categoryRegistrar
|
||||
self.hidePreviewsProvider = hidePreviewsProvider
|
||||
}
|
||||
|
||||
func requestAuthorization() {
|
||||
@@ -229,34 +197,29 @@ final class NotificationService {
|
||||
}
|
||||
|
||||
func sendMentionNotification(from sender: String, message: String) {
|
||||
let title = hidePreviews ? Redacted.mentionTitle : "🫵 you were mentioned by \(sender)"
|
||||
let body = hidePreviews ? Redacted.body : message
|
||||
let title = "🫵 you were mentioned by \(sender)"
|
||||
let 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 = hidePreviews ? Redacted.directMessageTitle : "🔒 DM from \(sender)"
|
||||
let body = hidePreviews ? Redacted.body : message
|
||||
let title = "🔒 DM from \(sender)"
|
||||
let 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) {
|
||||
// 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 title = "\(titlePrefix)\(geohash)"
|
||||
let identifier = "geo-activity-\(geohash)-\(Date().timeIntervalSince1970)"
|
||||
let deeplink = "bitchat://geohash/\(geohash)"
|
||||
let userInfo: [String: Any] = ["deeplink": deeplink]
|
||||
sendLocalNotification(title: title, body: body, identifier: identifier, userInfo: userInfo)
|
||||
sendLocalNotification(title: title, body: bodyPreview, identifier: identifier, userInfo: userInfo)
|
||||
}
|
||||
|
||||
func sendNetworkAvailableNotification(peerCount: Int) {
|
||||
|
||||
@@ -293,9 +293,6 @@ 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
|
||||
@@ -406,7 +403,6 @@ extension Transport {
|
||||
}
|
||||
|
||||
func purgeArchivedPublicMessages(from peerID: PeerID) {}
|
||||
func purgeAllArchivedPublicMessages() {}
|
||||
}
|
||||
|
||||
protocol TransportPeerEventsDelegate: AnyObject {
|
||||
|
||||
@@ -215,7 +215,22 @@ enum TransportConfig {
|
||||
static let nostrGeoRelayCount: Int = 5
|
||||
static let nostrGeohashSampleLookbackSeconds: TimeInterval = 300
|
||||
static let nostrGeohashSampleLimit: Int = 100
|
||||
static let nostrDMSubscribeLookbackSeconds: TimeInterval = 86400
|
||||
/// New iOS public-envelope timestamps are deliberately shifted into the
|
||||
/// past for privacy and relay compatibility.
|
||||
static let nostrPrivateEnvelopeTimestampFuzzSeconds: TimeInterval = 15 * 60
|
||||
/// Deployed Android clients can shift legacy kind-1059 timestamps by the
|
||||
/// full preceding 48 hours.
|
||||
static let nostrLegacyAndroidTimestampFuzzSeconds: TimeInterval = 48 * 60 * 60
|
||||
/// Private mail remains eligible for delivery for the same 24-hour window
|
||||
/// as the persistent sender outbox. The relay query must add timestamp
|
||||
/// randomization to that window rather than replacing it: an Android event
|
||||
/// sent at t0 can legitimately be stamped t0-48h and fetched at t0+24h.
|
||||
static let nostrPrivateEnvelopeDeliveryWindowSeconds: TimeInterval = 24 * 60 * 60
|
||||
static let nostrDMSubscribeClockSkewSeconds: TimeInterval = 15 * 60
|
||||
static let nostrDMSubscribeLookbackSeconds: TimeInterval =
|
||||
nostrPrivateEnvelopeDeliveryWindowSeconds
|
||||
+ nostrLegacyAndroidTimestampFuzzSeconds
|
||||
+ nostrDMSubscribeClockSkewSeconds
|
||||
// A sampled chat message this recent means "a conversation is happening
|
||||
// there" for the empty-timeline nearby-activity hint.
|
||||
static let uiGeohashChatActivityWindowSeconds: TimeInterval = 900
|
||||
@@ -243,11 +258,20 @@ enum TransportConfig {
|
||||
// Reconnect delays get ±20% random jitter so relays that dropped together
|
||||
// (e.g. a network blip) don't thundering-herd the same reconnect instant.
|
||||
static let nostrRelayBackoffJitterRatio: Double = 0.2
|
||||
static let nostrRelayDefaultFetchLimit: Int = 100
|
||||
/// Migration recovery uses one independent relay filter per wire kind so
|
||||
/// primary traffic cannot consume the legacy result budget (or vice
|
||||
/// versa). Five hundred per kind bounds startup work while preserving a
|
||||
/// materially deeper offline mailbox than the generic feed default.
|
||||
static let nostrPrivateEnvelopeFetchLimitPerKind: Int = 500
|
||||
// How many consecutive Tor-readiness waits (each bounded by TorManager's
|
||||
// bootstrap deadline) to attempt before unblocking pending EOSE callers.
|
||||
static let nostrTorReadyMaxWaitAttempts: Int = 3
|
||||
static let nostrPendingSendQueueCap: Int = 200
|
||||
/// Control-payload pairs (delivery/read acknowledgements and favorite
|
||||
/// notifications) that could not enter the relay queue. User messages do
|
||||
/// not use this queue: they fail visibly, while direct messages also
|
||||
/// remain in the router outbox.
|
||||
static let nostrPrivateEnvelopeRetryQueueCap: Int = 256
|
||||
// Sample interval for the send-queue overflow warning (first + every Nth
|
||||
// dropped event). Drops are ephemeral presence/geo traffic — log-only.
|
||||
static let nostrPendingSendDropLogInterval: Int = 10
|
||||
|
||||
@@ -733,26 +733,6 @@ 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,14 +21,6 @@ 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).
|
||||
@@ -41,19 +33,6 @@ 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 {
|
||||
@@ -62,19 +41,6 @@ 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)
|
||||
}
|
||||
@@ -93,24 +59,6 @@ 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
|
||||
@@ -138,10 +86,9 @@ final class ChatDeliveryCoordinator {
|
||||
|
||||
@MainActor
|
||||
func didReceiveReadReceipt(_ receipt: ReadReceipt) {
|
||||
updateAcknowledgedMessageDeliveryStatus(
|
||||
updateMessageDeliveryStatus(
|
||||
receipt.originalMessageID,
|
||||
status: .read(by: receipt.readerNickname, at: receipt.timestamp),
|
||||
from: [receipt.readerID]
|
||||
status: .read(by: receipt.readerNickname, at: receipt.timestamp)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -158,59 +105,17 @@ 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:
|
||||
// Terminalize only after the store accepted the transition.
|
||||
// Confirmed receipt — stop retaining the message for resend.
|
||||
context.markMessageDelivered(messageID)
|
||||
default:
|
||||
break
|
||||
}
|
||||
context.notifyUIChanged()
|
||||
return true
|
||||
}
|
||||
|
||||
/// 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:
|
||||
guard context.setDeliveryStatus(status, forMessageID: messageID) else {
|
||||
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
|
||||
}
|
||||
|
||||
@@ -85,13 +85,14 @@ 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)
|
||||
@discardableResult
|
||||
func sendGeohashPrivateMessage(
|
||||
_ content: String,
|
||||
toRecipientHex recipientHex: String,
|
||||
from identity: NostrIdentity,
|
||||
messageID: String
|
||||
) -> Bool
|
||||
func sendGeohashDeliveryAck(for messageID: String, toRecipientHex recipientHex: String, from identity: NostrIdentity)
|
||||
func sendGeohashReadReceipt(_ messageID: String, toRecipientHex recipientHex: String, from identity: NostrIdentity)
|
||||
|
||||
@@ -171,11 +172,6 @@ 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)
|
||||
}
|
||||
@@ -184,7 +180,13 @@ extension ChatViewModel: ChatPrivateConversationContext {
|
||||
meshService.sendReadReceipt(receipt, to: peerID)
|
||||
}
|
||||
|
||||
func sendGeohashPrivateMessage(_ content: String, toRecipientHex recipientHex: String, from identity: NostrIdentity, messageID: String) {
|
||||
@discardableResult
|
||||
func sendGeohashPrivateMessage(
|
||||
_ content: String,
|
||||
toRecipientHex recipientHex: String,
|
||||
from identity: NostrIdentity,
|
||||
messageID: String
|
||||
) -> Bool {
|
||||
makeGeohashNostrTransport().sendPrivateMessageGeohash(
|
||||
content: content,
|
||||
toRecipientHex: recipientHex,
|
||||
@@ -226,9 +228,16 @@ extension ChatViewModel: ChatPrivateConversationContext {
|
||||
NotificationService.shared.sendPrivateMessageNotification(from: senderName, message: message, peerID: peerID)
|
||||
}
|
||||
|
||||
private func makeGeohashNostrTransport() -> NostrTransport {
|
||||
let transport = NostrTransport(keychain: keychain, idBridge: idBridge)
|
||||
func makeGeohashNostrTransport(
|
||||
dependencies: NostrTransport.Dependencies? = nil
|
||||
) -> NostrTransport {
|
||||
let transport = NostrTransport(
|
||||
keychain: keychain,
|
||||
idBridge: idBridge,
|
||||
dependencies: dependencies
|
||||
)
|
||||
transport.senderPeerID = meshService.myPeerID
|
||||
transport.eventDelegate = self
|
||||
return transport
|
||||
}
|
||||
}
|
||||
@@ -237,7 +246,7 @@ extension ChatViewModel: ChatPrivateConversationContext {
|
||||
final class ChatPrivateConversationCoordinator {
|
||||
private unowned let context: any ChatPrivateConversationContext
|
||||
|
||||
// Outbox retries re-wrap the same message in fresh gift-wrap events, so
|
||||
// Outbox retries re-envelope the same message in fresh private events, so
|
||||
// relay-level event-ID dedup can't catch them; track inbound GeoDM
|
||||
// message IDs so each copy past the first costs one (already-deduped)
|
||||
// ack check and nothing else.
|
||||
@@ -260,60 +269,6 @@ 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 }
|
||||
|
||||
@@ -463,13 +418,21 @@ final class ChatPrivateConversationCoordinator {
|
||||
"GeoDM: local send mid=\(messageID.prefix(8))… to=\(recipientHex.prefix(8))… conv=\(peerID)",
|
||||
category: .session
|
||||
)
|
||||
context.sendGeohashPrivateMessage(
|
||||
let accepted = context.sendGeohashPrivateMessage(
|
||||
content,
|
||||
toRecipientHex: recipientHex,
|
||||
from: identity,
|
||||
messageID: messageID
|
||||
)
|
||||
context.setPrivateDeliveryStatus(.sent, forMessageID: messageID, peerID: peerID)
|
||||
let status: DeliveryStatus = accepted
|
||||
? .sent
|
||||
: .failed(
|
||||
reason: String(
|
||||
localized: "content.delivery.reason.not_delivered",
|
||||
comment: "Failure reason shown when a private message could not enter the relay delivery queue"
|
||||
)
|
||||
)
|
||||
context.setPrivateDeliveryStatus(status, forMessageID: messageID, peerID: peerID)
|
||||
} catch {
|
||||
context.setPrivateDeliveryStatus(
|
||||
.failed(
|
||||
@@ -528,8 +491,6 @@ final class ChatPrivateConversationCoordinator {
|
||||
return
|
||||
}
|
||||
|
||||
let conversationPeerID = consolidateAccountConversationAliases(for: convKey)
|
||||
|
||||
if context.privateChatsContainMessage(withID: messageId) { return }
|
||||
|
||||
let message = BitchatMessage(
|
||||
@@ -540,18 +501,18 @@ final class ChatPrivateConversationCoordinator {
|
||||
isRelay: false,
|
||||
isPrivate: true,
|
||||
recipientNickname: context.nickname,
|
||||
senderPeerID: conversationPeerID,
|
||||
senderPeerID: convKey,
|
||||
deliveryStatus: .delivered(to: context.nickname, at: Date())
|
||||
)
|
||||
|
||||
context.appendPrivateMessage(message, to: conversationPeerID)
|
||||
context.appendPrivateMessage(message, to: convKey)
|
||||
|
||||
let isViewing = context.selectedPrivateChatPeer == conversationPeerID
|
||||
let isViewing = context.selectedPrivateChatPeer == convKey
|
||||
let wasReadBefore = context.sentReadReceipts.contains(messageId)
|
||||
let isRecentMessage = Date().timeIntervalSince(messageTimestamp) < 30
|
||||
let shouldMarkUnread = !wasReadBefore && !isViewing && isRecentMessage
|
||||
if shouldMarkUnread {
|
||||
context.markPrivateChatUnread(conversationPeerID)
|
||||
context.markPrivateChatUnread(convKey)
|
||||
}
|
||||
|
||||
if isViewing {
|
||||
@@ -559,7 +520,7 @@ final class ChatPrivateConversationCoordinator {
|
||||
}
|
||||
|
||||
if !isViewing && shouldMarkUnread {
|
||||
context.notifyPrivateMessage(from: senderName, message: pm.content, peerID: conversationPeerID)
|
||||
context.notifyPrivateMessage(from: senderName, message: pm.content, peerID: convKey)
|
||||
}
|
||||
|
||||
context.notifyUIChanged()
|
||||
@@ -568,32 +529,17 @@ final class ChatPrivateConversationCoordinator {
|
||||
func handleDelivered(_ payload: NoisePayload, senderPubkey: String, convKey: PeerID) {
|
||||
guard let messageID = String(data: payload.data, encoding: .utf8) else { return }
|
||||
|
||||
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(
|
||||
if context.privateChat(convKey, containsMessageWithID: messageID) {
|
||||
context.setPrivateDeliveryStatus(
|
||||
.delivered(to: context.displayNameForNostrPubkey(senderPubkey), at: Date()),
|
||||
forMessageID: messageID,
|
||||
peerID: conversationPeerID
|
||||
peerID: convKey
|
||||
)
|
||||
if didChange {
|
||||
context.notifyUIChanged()
|
||||
}
|
||||
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
|
||||
@@ -605,29 +551,14 @@ final class ChatPrivateConversationCoordinator {
|
||||
func handleReadReceipt(_ payload: NoisePayload, senderPubkey: String, convKey: PeerID) {
|
||||
guard let messageID = String(data: payload.data, encoding: .utf8) else { return }
|
||||
|
||||
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(
|
||||
if context.privateChat(convKey, containsMessageWithID: messageID) {
|
||||
context.setPrivateDeliveryStatus(
|
||||
.read(by: context.displayNameForNostrPubkey(senderPubkey), at: Date()),
|
||||
forMessageID: messageID,
|
||||
peerID: conversationPeerID
|
||||
peerID: convKey
|
||||
)
|
||||
if didChange {
|
||||
context.notifyUIChanged()
|
||||
}
|
||||
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,9 +44,6 @@ 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)
|
||||
|
||||
@@ -292,14 +289,12 @@ 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 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.
|
||||
// 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.
|
||||
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,15 +62,10 @@ protocol ChatTransportEventContext: AnyObject {
|
||||
func sendMeshDeliveryAck(for messageID: String, to peerID: PeerID)
|
||||
|
||||
// MARK: Delivery status
|
||||
/// 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.
|
||||
/// Applies the status to every known location of the message.
|
||||
/// Returns `false` when no message with that ID was updated.
|
||||
@discardableResult
|
||||
func applyAcknowledgedMessageDeliveryStatus(
|
||||
_ messageID: String,
|
||||
status: DeliveryStatus,
|
||||
from peerIDAliases: Set<PeerID>
|
||||
) -> Bool
|
||||
func applyMessageDeliveryStatus(_ messageID: String, status: DeliveryStatus) -> Bool
|
||||
func deliveryStatus(for messageID: String) -> DeliveryStatus?
|
||||
|
||||
// MARK: Verification payloads
|
||||
@@ -127,16 +122,8 @@ extension ChatViewModel: ChatTransportEventContext {
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
func applyAcknowledgedMessageDeliveryStatus(
|
||||
_ messageID: String,
|
||||
status: DeliveryStatus,
|
||||
from peerIDAliases: Set<PeerID>
|
||||
) -> Bool {
|
||||
deliveryCoordinator.updateAcknowledgedMessageDeliveryStatus(
|
||||
messageID,
|
||||
status: status,
|
||||
from: peerIDAliases
|
||||
)
|
||||
func applyMessageDeliveryStatus(_ messageID: String, status: DeliveryStatus) -> Bool {
|
||||
deliveryCoordinator.updateMessageDeliveryStatus(messageID, status: status)
|
||||
}
|
||||
|
||||
func deliveryStatus(for messageID: String) -> DeliveryStatus? {
|
||||
@@ -459,10 +446,9 @@ private extension ChatTransportEventCoordinator {
|
||||
guard let messageID = String(data: payload, encoding: .utf8) else { return }
|
||||
|
||||
let name = deliveryStatusName(for: peerID, in: context)
|
||||
let didUpdate = context.applyAcknowledgedMessageDeliveryStatus(
|
||||
let didUpdate = context.applyMessageDeliveryStatus(
|
||||
messageID,
|
||||
status: .delivered(to: name, at: Date()),
|
||||
from: receiptPeerAliases(for: peerID, in: context)
|
||||
status: .delivered(to: name, at: Date())
|
||||
)
|
||||
|
||||
if !didUpdate {
|
||||
@@ -477,10 +463,9 @@ private extension ChatTransportEventCoordinator {
|
||||
guard let messageID = String(data: payload, encoding: .utf8) else { return }
|
||||
|
||||
let name = deliveryStatusName(for: peerID, in: context)
|
||||
let didUpdate = context.applyAcknowledgedMessageDeliveryStatus(
|
||||
let didUpdate = context.applyMessageDeliveryStatus(
|
||||
messageID,
|
||||
status: .read(by: name, at: Date()),
|
||||
from: receiptPeerAliases(for: peerID, in: context)
|
||||
status: .read(by: name, at: Date())
|
||||
)
|
||||
|
||||
if !didUpdate {
|
||||
@@ -518,21 +503,4 @@ 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,10 +59,6 @@ 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)
|
||||
|
||||
@@ -125,10 +121,6 @@ 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)
|
||||
}
|
||||
@@ -224,37 +216,16 @@ final class ChatVerificationCoordinator {
|
||||
|
||||
self.context.invalidateEncryptionCache(for: peerID)
|
||||
|
||||
var authenticatedStablePeerID: PeerID?
|
||||
if let keyData = self.context.noiseSessionPublicKeyData(for: peerID) {
|
||||
if self.context.cachedStablePeerID(for: peerID) == nil,
|
||||
let keyData = self.context.noiseSessionPublicKeyData(for: peerID) {
|
||||
let stablePeerID = PeerID(hexData: keyData)
|
||||
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)
|
||||
}
|
||||
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,8 +363,6 @@ 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?
|
||||
@@ -1068,10 +1066,6 @@ 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.)
|
||||
@@ -1634,10 +1628,6 @@ 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()
|
||||
@@ -1687,6 +1677,7 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage
|
||||
// Drop relay subscriptions, handlers, pending sends, and replay state.
|
||||
// Geohash DM handlers can capture pre-wipe Nostr identities, so a plain
|
||||
// disconnect is not enough here.
|
||||
NostrTransport.resetControlRetriesForPanicWipe()
|
||||
NostrRelayManager.shared.resetForPanicWipe()
|
||||
// Clearing relay handlers stops NEW events, but a detached gift-wrap
|
||||
// decrypt spawned just before the wipe still holds a pre-wipe key and
|
||||
|
||||
@@ -41,10 +41,11 @@ struct ChatViewModelServiceBundle {
|
||||
self.privateChatManager = privateChatManager
|
||||
self.unifiedPeerService = unifiedPeerService
|
||||
self.autocompleteService = AutocompleteService()
|
||||
// Persist processed gift-wrap event IDs: NIP-59 randomizes their
|
||||
// timestamps, so the 24h-lookback DM subscriptions redeliver the same
|
||||
// events on every launch and only a cross-launch record stops the
|
||||
// reprocessing (re-sent DELIVERED bursts, phantom-ack noise).
|
||||
// Persist processed private-envelope event IDs: legacy Android can
|
||||
// randomize timestamps across the full 72h15m mailbox lookback, so DM
|
||||
// subscriptions redeliver the same events on every launch and only a
|
||||
// cross-launch record stops the reprocessing (re-sent DELIVERED
|
||||
// bursts, phantom-ack noise).
|
||||
self.deduplicationService = MessageDeduplicationService(nostrEventStore: NostrProcessedEventStore())
|
||||
self.publicMessagePipeline = PublicMessagePipeline()
|
||||
}
|
||||
@@ -176,7 +177,7 @@ private extension ChatViewModelBootstrapper {
|
||||
|
||||
func configureTransport() {
|
||||
viewModel.meshService.delegate = viewModel
|
||||
viewModel.meshService.eventDelegate = viewModel
|
||||
viewModel.messageRouter.setEventDelegate(viewModel)
|
||||
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + TransportConfig.uiStartupInitialDelaySeconds) { [weak viewModel] in
|
||||
guard let viewModel else { return }
|
||||
@@ -558,7 +559,7 @@ private extension ChatViewModelBootstrapper {
|
||||
// Default (DM) relays: drops need the standing global relay set,
|
||||
// not geo relays — sender and recipient share no cell.
|
||||
// This confirmed path never falls back to the volatile relay
|
||||
// queue; bridge dedup is committed only after NIP-20 OK.
|
||||
// queue; bridge dedup is committed only after NIP-01 `OK`.
|
||||
NostrRelayManager.shared.sendEventImmediately(event, completion: completion)
|
||||
}
|
||||
courier.openSubscription = { tagsHex in
|
||||
|
||||
@@ -21,8 +21,8 @@ extension ChatViewModel {
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func subscribeGiftWrap(_ giftWrap: NostrEvent, id: NostrIdentity) {
|
||||
nostrCoordinator.inbound.subscribeGiftWrap(giftWrap, id: id)
|
||||
func subscribePrivateEnvelope(_ envelope: NostrEvent, id: NostrIdentity) {
|
||||
nostrCoordinator.inbound.subscribePrivateEnvelope(envelope, id: id)
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@@ -36,8 +36,8 @@ extension ChatViewModel {
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func handleGiftWrap(_ giftWrap: NostrEvent, id: NostrIdentity) {
|
||||
nostrCoordinator.inbound.handleGiftWrap(giftWrap, id: id)
|
||||
func handlePrivateEnvelope(_ envelope: NostrEvent, id: NostrIdentity) {
|
||||
nostrCoordinator.inbound.handlePrivateEnvelope(envelope, id: id)
|
||||
}
|
||||
|
||||
@MainActor
|
||||
|
||||
@@ -15,8 +15,6 @@ 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)
|
||||
@@ -39,7 +37,6 @@ 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)
|
||||
@@ -57,35 +54,11 @@ 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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -108,7 +108,7 @@ extension ChatViewModel: GeohashSubscriptionContext {
|
||||
}
|
||||
|
||||
/// Owns subscription IDs and relay lifecycle for geohash channels, geohash
|
||||
/// DMs, the account gift-wrap mailbox, and background geohash sampling. The
|
||||
/// DMs, the account private-envelope mailbox, and background geohash sampling. The
|
||||
/// only component that talks to `NostrRelayManager`; inbound events are
|
||||
/// forwarded to `NostrInboundPipeline` / `GeoPresenceTracker`.
|
||||
final class GeohashSubscriptionManager {
|
||||
@@ -162,13 +162,13 @@ final class GeohashSubscriptionManager {
|
||||
if let identity = try? context.deriveNostrIdentity(forGeohash: channel.geohash) {
|
||||
let dmSub = "geo-dm-\(channel.geohash)"
|
||||
context.setGeoDmSubscriptionID(dmSub)
|
||||
let dmFilter = NostrFilter.giftWrapsFor(
|
||||
let dmFilters = NostrFilter.privateEnvelopeFiltersFor(
|
||||
pubkey: identity.publicKeyHex,
|
||||
since: Date().addingTimeInterval(-TransportConfig.nostrDMSubscribeLookbackSeconds)
|
||||
)
|
||||
NostrRelayManager.shared.subscribe(filter: dmFilter, id: dmSub) { [weak self] giftWrap in
|
||||
NostrRelayManager.shared.subscribe(filters: dmFilters, id: dmSub) { [weak self] envelope in
|
||||
Task { @MainActor [weak self] in
|
||||
self?.inbound.subscribeGiftWrap(giftWrap, id: identity)
|
||||
self?.inbound.subscribePrivateEnvelope(envelope, id: identity)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -260,13 +260,13 @@ final class GeohashSubscriptionManager {
|
||||
if TorManager.shared.isReady {
|
||||
SecureLogger.debug("GeoDM: subscribing DMs pub=\(identity.publicKeyHex.prefix(8))… sub=\(dmSub)", category: .session)
|
||||
}
|
||||
let dmFilter = NostrFilter.giftWrapsFor(
|
||||
let dmFilters = NostrFilter.privateEnvelopeFiltersFor(
|
||||
pubkey: identity.publicKeyHex,
|
||||
since: Date().addingTimeInterval(-TransportConfig.nostrDMSubscribeLookbackSeconds)
|
||||
)
|
||||
NostrRelayManager.shared.subscribe(filter: dmFilter, id: dmSub) { [weak self] giftWrap in
|
||||
NostrRelayManager.shared.subscribe(filters: dmFilters, id: dmSub) { [weak self] envelope in
|
||||
Task { @MainActor [weak self] in
|
||||
self?.inbound.handleGiftWrap(giftWrap, id: identity)
|
||||
self?.inbound.handlePrivateEnvelope(envelope, id: identity)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -388,14 +388,14 @@ final class GeohashSubscriptionManager {
|
||||
category: .session
|
||||
)
|
||||
|
||||
let filter = NostrFilter.giftWrapsFor(
|
||||
let filters = NostrFilter.privateEnvelopeFiltersFor(
|
||||
pubkey: currentIdentity.publicKeyHex,
|
||||
since: Date().addingTimeInterval(-TransportConfig.nostrDMSubscribeLookbackSeconds)
|
||||
)
|
||||
|
||||
context.nostrRelayManager?.subscribe(filter: filter, id: "chat-messages") { [weak self] event in
|
||||
context.nostrRelayManager?.subscribe(filters: filters, id: "chat-messages") { [weak self] event in
|
||||
Task { @MainActor [weak self] in
|
||||
self?.inbound.handleNostrMessage(event)
|
||||
self?.inbound.handleAccountPrivateEnvelope(event)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,13 +86,21 @@ extension ChatViewModel: NostrInboundPipelineContext {
|
||||
/// pipeline (which records events into its own dedup cache only AFTER
|
||||
/// verification, so forged copies can't suppress genuine events). This
|
||||
/// pipeline therefore never re-verifies; it keeps its own event-ID dedup
|
||||
/// (cheap main-actor lookups) and moves NIP-17 gift-wrap decryption — two
|
||||
/// (cheap main-actor lookups) and moves private-envelope decryption — two
|
||||
/// ECDH+ChaCha layers — off the main actor with an atomic main-actor
|
||||
/// check-and-record.
|
||||
final class NostrInboundPipeline {
|
||||
private weak var context: (any NostrInboundPipelineContext)?
|
||||
private let presence: GeoPresenceTracker
|
||||
private var geoEventLogCount = 0
|
||||
// During the coordinated wire-format migration, one logical private
|
||||
// payload is published under both primary and compatibility formats. Outer
|
||||
// event IDs differ, so collapse the authenticated embedded payload before
|
||||
// invoking message/ack side effects. Keep this bounded like the outer-ID
|
||||
// caches; the recipient and authenticated sender are part of the key.
|
||||
private var recentPrivatePayloadFormats: [String: UInt8] = [:]
|
||||
private var recentPrivatePayloadKeyOrder: [String] = []
|
||||
private static let privatePayloadDedupCapacity = 2_048
|
||||
|
||||
/// Monotonic panic-wipe generation for this pipeline. A panic wipe clears
|
||||
/// relay handlers so no NEW events flow, but a detached decrypt task
|
||||
@@ -286,13 +294,13 @@ final class NostrInboundPipeline {
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func subscribeGiftWrap(_ giftWrap: NostrEvent, id: NostrIdentity) {
|
||||
func subscribePrivateEnvelope(_ envelope: NostrEvent, id: NostrIdentity) {
|
||||
guard let context else { return }
|
||||
// Cheap dedup pre-check only; processGeohashGiftWrap does the
|
||||
// Cheap dedup pre-check only; processGeohashPrivateEnvelope does the
|
||||
// authoritative main-actor check-and-record before the off-main
|
||||
// NIP-17 unwrap. The outer signature was already verified (exactly
|
||||
// once, off the main actor) by NostrRelayManager.
|
||||
guard !context.hasProcessedNostrEvent(giftWrap.id) else { return }
|
||||
// private-envelope unwrap. The outer signature was already verified
|
||||
// (exactly once, off the main actor) by NostrRelayManager.
|
||||
guard !context.hasProcessedNostrEvent(envelope.id) else { return }
|
||||
|
||||
// Capture the wipe generation at spawn, alongside the per-geohash
|
||||
// identity (private key) the detached task strongly captures. A panic
|
||||
@@ -300,29 +308,29 @@ final class NostrInboundPipeline {
|
||||
// drops its result instead of delivering plaintext post-wipe.
|
||||
let wipeGeneration = self.wipeGeneration
|
||||
Task.detached(priority: .userInitiated) { [weak self] in
|
||||
await self?.processGeohashGiftWrap(giftWrap, id: id, verbose: false, wipeGeneration: wipeGeneration)
|
||||
await self?.processGeohashPrivateEnvelope(envelope, id: id, verbose: false, wipeGeneration: wipeGeneration)
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func handleGiftWrap(_ giftWrap: NostrEvent, id: NostrIdentity) {
|
||||
func handlePrivateEnvelope(_ envelope: NostrEvent, id: NostrIdentity) {
|
||||
guard let context else { return }
|
||||
// Cheap dedup pre-check only; see subscribeGiftWrap.
|
||||
if context.hasProcessedNostrEvent(giftWrap.id) {
|
||||
// Cheap dedup pre-check only; see subscribePrivateEnvelope.
|
||||
if context.hasProcessedNostrEvent(envelope.id) {
|
||||
return
|
||||
}
|
||||
|
||||
// Spawn-time wipe-generation capture; see subscribeGiftWrap.
|
||||
// Spawn-time wipe-generation capture; see subscribePrivateEnvelope.
|
||||
let wipeGeneration = self.wipeGeneration
|
||||
Task.detached(priority: .userInitiated) { [weak self] in
|
||||
await self?.processGeohashGiftWrap(giftWrap, id: id, verbose: true, wipeGeneration: wipeGeneration)
|
||||
await self?.processGeohashPrivateEnvelope(envelope, id: id, verbose: true, wipeGeneration: wipeGeneration)
|
||||
}
|
||||
}
|
||||
|
||||
/// Geohash-DM gift wrap ingest. The NIP-17 unwrap (two ECDH+ChaCha
|
||||
/// layers) runs off the main actor; results hop back for state updates.
|
||||
/// `verbose` keeps `handleGiftWrap`'s decrypt logging without adding it
|
||||
/// to the sampling path.
|
||||
/// Geohash-DM private-envelope ingest. The envelope unwrap (two
|
||||
/// ECDH+ChaCha layers) runs off the main actor; results hop back for
|
||||
/// state updates. `verbose` keeps `handlePrivateEnvelope`'s decrypt
|
||||
/// logging without adding it to the sampling path.
|
||||
///
|
||||
/// `wipeGeneration` is this pipeline's generation captured at spawn (the
|
||||
/// moment the pre-wipe `id` was captured); a mismatch at either main-actor
|
||||
@@ -330,8 +338,8 @@ final class NostrInboundPipeline {
|
||||
/// decrypting (first hop) or without delivering the plaintext (second
|
||||
/// hop) — the captured identity and any decrypted material are simply
|
||||
/// dropped with the task.
|
||||
private func processGeohashGiftWrap(
|
||||
_ giftWrap: NostrEvent,
|
||||
private func processGeohashPrivateEnvelope(
|
||||
_ envelope: NostrEvent,
|
||||
id: NostrIdentity,
|
||||
verbose: Bool,
|
||||
wipeGeneration: UInt64
|
||||
@@ -341,25 +349,25 @@ final class NostrInboundPipeline {
|
||||
// concurrent detached tasks can't both process the same event.
|
||||
let alreadyProcessed: Bool = await MainActor.run {
|
||||
guard self.wipeGeneration == wipeGeneration else { return true }
|
||||
if context.hasProcessedNostrEvent(giftWrap.id) { return true }
|
||||
context.recordProcessedNostrEvent(giftWrap.id)
|
||||
if context.hasProcessedNostrEvent(envelope.id) { return true }
|
||||
context.recordProcessedNostrEvent(envelope.id)
|
||||
return false
|
||||
}
|
||||
if alreadyProcessed { return }
|
||||
|
||||
guard let (content, senderPubkey, rumorTs) = try? NostrProtocol.decryptPrivateMessage(
|
||||
giftWrap: giftWrap,
|
||||
guard let (content, senderPubkey, messageTs) = try? NostrProtocol.decryptPrivateEnvelope(
|
||||
envelope: envelope,
|
||||
recipientIdentity: id
|
||||
) else {
|
||||
if verbose {
|
||||
SecureLogger.warning("GeoDM: failed decrypt giftWrap id=\(giftWrap.id.prefix(8))…", category: .session)
|
||||
SecureLogger.warning("GeoDM: failed decrypt private envelope id=\(envelope.id.prefix(8))…", category: .session)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if verbose {
|
||||
SecureLogger.debug(
|
||||
"GeoDM: decrypted gift-wrap id=\(giftWrap.id.prefix(16))... from=\(senderPubkey.prefix(8))...",
|
||||
"GeoDM: decrypted private envelope id=\(envelope.id.prefix(16))... from=\(senderPubkey.prefix(8))...",
|
||||
category: .session
|
||||
)
|
||||
}
|
||||
@@ -375,13 +383,19 @@ final class NostrInboundPipeline {
|
||||
else {
|
||||
return
|
||||
}
|
||||
guard self.shouldProcessPrivatePayload(
|
||||
payload,
|
||||
senderPubkey: senderPubkey,
|
||||
recipientPubkey: id.publicKeyHex,
|
||||
envelopeKind: envelope.kind
|
||||
) else { return }
|
||||
|
||||
let convKey = PeerID(nostr_: senderPubkey)
|
||||
context.registerNostrKeyMapping(senderPubkey, for: convKey)
|
||||
|
||||
switch payload.type {
|
||||
case .privateMessage:
|
||||
let messageTimestamp = Date(timeIntervalSince1970: TimeInterval(rumorTs))
|
||||
let messageTimestamp = Date(timeIntervalSince1970: TimeInterval(messageTs))
|
||||
context.handlePrivateMessage(
|
||||
payload,
|
||||
senderPubkey: senderPubkey,
|
||||
@@ -404,44 +418,44 @@ final class NostrInboundPipeline {
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func handleNostrMessage(_ giftWrap: NostrEvent) {
|
||||
func handleAccountPrivateEnvelope(_ envelope: NostrEvent) {
|
||||
guard let context else { return }
|
||||
// Cheap dedup pre-check only; processNostrMessage does the
|
||||
// authoritative check-and-record before the off-main NIP-17 unwrap.
|
||||
// The outer signature was already verified (exactly once, off the
|
||||
// main actor) by NostrRelayManager, and only verified events are
|
||||
// Cheap dedup pre-check only; processAccountPrivateEnvelope does the
|
||||
// authoritative check-and-record before the off-main private-envelope
|
||||
// unwrap. The outer signature was already verified (exactly once, off
|
||||
// the main actor) by NostrRelayManager, and only verified events are
|
||||
// recorded, so a forged-signature copy can never poison the dedup
|
||||
// set and suppress the genuine event.
|
||||
if context.hasProcessedNostrEvent(giftWrap.id) { return }
|
||||
if context.hasProcessedNostrEvent(envelope.id) { return }
|
||||
|
||||
Task.detached(priority: .userInitiated) { [weak self] in
|
||||
await self?.processNostrMessage(giftWrap)
|
||||
await self?.processAccountPrivateEnvelope(envelope)
|
||||
}
|
||||
}
|
||||
|
||||
func processNostrMessage(_ giftWrap: NostrEvent) async {
|
||||
func processAccountPrivateEnvelope(_ envelope: NostrEvent) async {
|
||||
guard let context else { return }
|
||||
// Authoritative check-and-record, atomic on the main actor so two
|
||||
// concurrent detached tasks can't both process the same event.
|
||||
let alreadyProcessed: Bool = await MainActor.run {
|
||||
if context.hasProcessedNostrEvent(giftWrap.id) { return true }
|
||||
context.recordProcessedNostrEvent(giftWrap.id)
|
||||
if context.hasProcessedNostrEvent(envelope.id) { return true }
|
||||
context.recordProcessedNostrEvent(envelope.id)
|
||||
return false
|
||||
}
|
||||
if alreadyProcessed { return }
|
||||
// Fetch the identity and the wipe generation in ONE main-actor hop:
|
||||
// the generation then vouches for exactly this identity. A wipe after
|
||||
// this point bumps the generation and the delivery hop below drops
|
||||
// the decrypted result (same guard as processGeohashGiftWrap; this
|
||||
// account-mailbox path had the identical hazard).
|
||||
// the decrypted result (same guard as processGeohashPrivateEnvelope;
|
||||
// this account-mailbox path had the identical hazard).
|
||||
let (currentIdentity, wipeGeneration): (NostrIdentity?, UInt64) = await MainActor.run {
|
||||
(context.currentNostrIdentity(), self.wipeGeneration)
|
||||
}
|
||||
guard let currentIdentity else { return }
|
||||
|
||||
do {
|
||||
let (content, senderPubkey, rumorTimestamp) = try NostrProtocol.decryptPrivateMessage(
|
||||
giftWrap: giftWrap,
|
||||
let (content, senderPubkey, messageTimestampSeconds) = try NostrProtocol.decryptPrivateEnvelope(
|
||||
envelope: envelope,
|
||||
recipientIdentity: currentIdentity
|
||||
)
|
||||
|
||||
@@ -465,11 +479,17 @@ final class NostrInboundPipeline {
|
||||
|
||||
if packet.type == MessageType.noiseEncrypted.rawValue,
|
||||
let payload = NoisePayload.decode(packet.payload) {
|
||||
let messageTimestamp = Date(timeIntervalSince1970: TimeInterval(rumorTimestamp))
|
||||
let messageTimestamp = Date(timeIntervalSince1970: TimeInterval(messageTimestampSeconds))
|
||||
await MainActor.run {
|
||||
// Drop pre-wipe plaintext if a panic wipe landed
|
||||
// during the off-main decrypt (see above).
|
||||
guard self.wipeGeneration == wipeGeneration else { return }
|
||||
guard self.shouldProcessPrivatePayload(
|
||||
payload,
|
||||
senderPubkey: senderPubkey,
|
||||
recipientPubkey: currentIdentity.publicKeyHex,
|
||||
envelopeKind: envelope.kind
|
||||
) else { return }
|
||||
context.registerNostrKeyMapping(senderPubkey, for: targetPeerID)
|
||||
|
||||
switch payload.type {
|
||||
@@ -543,6 +563,47 @@ final class NostrInboundPipeline {
|
||||
}
|
||||
|
||||
private extension NostrInboundPipeline {
|
||||
@MainActor
|
||||
func shouldProcessPrivatePayload(
|
||||
_ payload: NoisePayload,
|
||||
senderPubkey: String,
|
||||
recipientPubkey: String,
|
||||
envelopeKind: Int
|
||||
) -> Bool {
|
||||
let digest = payload.encode().sha256Fingerprint()
|
||||
let key = "\(recipientPubkey.lowercased()):\(senderPubkey.lowercased()):\(digest)"
|
||||
let formatBit: UInt8
|
||||
switch envelopeKind {
|
||||
case NostrProtocol.EventKind.privateEnvelope.rawValue:
|
||||
formatBit = 1 << 0
|
||||
case NostrProtocol.EventKind.legacyNIP59GiftWrap.rawValue:
|
||||
formatBit = 1 << 1
|
||||
default:
|
||||
return true
|
||||
}
|
||||
|
||||
if let observedFormats = recentPrivatePayloadFormats[key] {
|
||||
if observedFormats & formatBit != 0 {
|
||||
// A same-format re-envelope is a delivery retry. Let it reach
|
||||
// the coordinator so a lost DELIVERED acknowledgement can be
|
||||
// sent again; downstream message-ID dedup prevents rerendering.
|
||||
return true
|
||||
}
|
||||
// The same authenticated payload under the other migration format
|
||||
// is the compatibility twin, not a new message or acknowledgement.
|
||||
recentPrivatePayloadFormats[key] = observedFormats | formatBit
|
||||
return false
|
||||
}
|
||||
|
||||
recentPrivatePayloadFormats[key] = formatBit
|
||||
recentPrivatePayloadKeyOrder.append(key)
|
||||
if recentPrivatePayloadKeyOrder.count > Self.privatePayloadDedupCapacity {
|
||||
let evicted = recentPrivatePayloadKeyOrder.removeFirst()
|
||||
recentPrivatePayloadFormats.removeValue(forKey: evicted)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
@MainActor
|
||||
static func decodeEmbeddedBitChatPacket(from content: String) -> BitchatPacket? {
|
||||
guard content.hasPrefix("bitchat1:") else { return nil }
|
||||
|
||||
@@ -21,10 +21,6 @@ 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.
|
||||
@@ -83,41 +79,10 @@ 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"
|
||||
// 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 torSubtitle: LocalizedStringKey = "location_channels.tor.subtitle"
|
||||
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")
|
||||
@@ -445,22 +410,11 @@ struct AppInfoView: View {
|
||||
settingsCard {
|
||||
settingToggle(
|
||||
title: Text(Strings.Settings.torTitle),
|
||||
subtitle: Text(verbatim: Strings.Settings.torSubtitle),
|
||||
subtitle: Text(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
|
||||
@@ -523,26 +477,6 @@ 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) {
|
||||
@@ -604,108 +538,6 @@ 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,14 +73,7 @@ struct ContentComposerView: View {
|
||||
.textInputAutocapitalization(.sentences)
|
||||
#endif
|
||||
.submitLabel(.send)
|
||||
.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
|
||||
}
|
||||
.onSubmit(onSendMessage)
|
||||
.padding(.vertical, theme.usesGlassChrome ? 8 : 4)
|
||||
.padding(.horizontal, 6)
|
||||
.themedInputBackground()
|
||||
|
||||
@@ -6,28 +6,11 @@ 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
|
||||
@@ -40,7 +23,6 @@ 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
|
||||
@@ -53,75 +35,6 @@ 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 {
|
||||
@@ -165,8 +78,7 @@ struct ContentPeopleSheetView: View {
|
||||
#endif
|
||||
} else {
|
||||
ContentPeopleListView(
|
||||
showSidebar: $showSidebar,
|
||||
showVerifySheet: $showVerifySheet
|
||||
showSidebar: $showSidebar
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -270,27 +182,6 @@ 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -305,7 +196,8 @@ private struct ContentPeopleListView: View {
|
||||
@ThemedPalette private var palette
|
||||
|
||||
@Binding var showSidebar: Bool
|
||||
@Binding var showVerifySheet: Bool
|
||||
|
||||
@State private var showVerifySheet = false
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
|
||||
@@ -14,61 +14,6 @@ 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 {
|
||||
@@ -98,7 +43,6 @@ 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?
|
||||
@@ -136,80 +80,6 @@ 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 {
|
||||
@@ -251,20 +121,11 @@ struct ContentView: View {
|
||||
}
|
||||
.sheet(
|
||||
isPresented: Binding(
|
||||
get: { isPeopleSheetPresented },
|
||||
get: { showSidebar || selectedPrivatePeerID != nil },
|
||||
set: { isPresented in
|
||||
if !isPresented {
|
||||
showSidebar = false
|
||||
// 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()
|
||||
}
|
||||
privateConversationModel.endConversation()
|
||||
}
|
||||
}
|
||||
)
|
||||
@@ -365,7 +226,7 @@ struct ContentView: View {
|
||||
ImagePreviewView(url: url)
|
||||
}
|
||||
}
|
||||
.alert("Recording Error", isPresented: rootVoiceAlertBinding, actions: {
|
||||
.alert("Recording Error", isPresented: $voiceRecordingVM.showAlert, actions: {
|
||||
Button("common.ok", role: .cancel) {}
|
||||
if voiceRecordingVM.state == .permissionDenied {
|
||||
Button("location_channels.action.open_settings") {
|
||||
@@ -375,7 +236,7 @@ struct ContentView: View {
|
||||
}, message: {
|
||||
Text(voiceRecordingVM.state.alertMessage)
|
||||
})
|
||||
.alert("content.alert.bluetooth_required.title", isPresented: rootBluetoothAlertBinding) {
|
||||
.alert("content.alert.bluetooth_required.title", isPresented: $appChromeModel.showBluetoothAlert) {
|
||||
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.negativeWaitWindow
|
||||
timeout: TestConstants.shortTimeout
|
||||
)
|
||||
#expect(!receivedDuplicate)
|
||||
|
||||
@@ -117,7 +117,7 @@ struct BLEServiceCoreTests {
|
||||
|
||||
let unsignedRelayed = await TestHelpers.waitUntil(
|
||||
{ outbound.count(ofType: .leave) > 0 },
|
||||
timeout: TestConstants.negativeWaitWindow
|
||||
timeout: TestConstants.shortTimeout
|
||||
)
|
||||
#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.negativeWaitWindow
|
||||
timeout: TestConstants.shortTimeout
|
||||
)
|
||||
#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.settleTimeout
|
||||
timeout: TestConstants.defaultTimeout
|
||||
)
|
||||
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.negativeWaitWindow
|
||||
timeout: TestConstants.shortTimeout
|
||||
)
|
||||
#expect(!exceededBudget)
|
||||
#expect(outbound.count(ofType: .pong) == budget)
|
||||
|
||||
@@ -243,7 +243,7 @@ private func drainMainQueue() async {
|
||||
|
||||
/// Exercises `ChatNostrCoordinator` against `MockChatNostrContext` with no
|
||||
/// `ChatViewModel`. Scoped to the inbound event pipeline (dedup, presence,
|
||||
/// public-message ingest), gift-wrap DM ingest, key mapping, channel-switch
|
||||
/// public-message ingest), private-envelope ingest, key mapping, channel-switch
|
||||
/// teardown, embedded ack flows, and — now that favorites and notifications
|
||||
/// are injected through the context — the favorite-notification ingest and
|
||||
/// the sampled-geohash notification cooldown. Flows that hit live singletons
|
||||
@@ -335,7 +335,7 @@ struct ChatNostrCoordinatorContextTests {
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func handleGiftWrap_routesEmbeddedPrivateMessageAndDeduplicates() async throws {
|
||||
func handlePrivateEnvelope_routesEmbeddedPrivateMessageAndDeduplicates() async throws {
|
||||
let context = MockChatNostrContext()
|
||||
let coordinator = ChatNostrCoordinator(context: context)
|
||||
|
||||
@@ -346,20 +346,30 @@ struct ChatNostrCoordinatorContextTests {
|
||||
messageID: "gm-1",
|
||||
senderPeerID: PeerID(str: "aabbccddeeff0011")
|
||||
))
|
||||
let giftWrap = try NostrProtocol.createPrivateMessage(
|
||||
let envelopes = try NostrProtocol.createPrivateEnvelopePublicationBatch(
|
||||
content: embedded,
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
)
|
||||
|
||||
coordinator.inbound.handleGiftWrap(giftWrap, id: recipient)
|
||||
for envelope in envelopes {
|
||||
coordinator.inbound.handlePrivateEnvelope(envelope, id: recipient)
|
||||
}
|
||||
|
||||
// The NIP-17 unwrap runs off the main actor; wait for the hop back.
|
||||
// The envelope unwrap runs off the main actor; wait for the hop back.
|
||||
let convKey = PeerID(nostr_: sender.publicKeyHex)
|
||||
let routed = await TestHelpers.waitUntil({ context.handledPrivateMessages.count == 1 })
|
||||
let routed = await TestHelpers.waitUntil({
|
||||
context.handledPrivateMessages.count >= 1
|
||||
&& context.recordedNostrEventIDs.count == envelopes.count
|
||||
})
|
||||
#expect(routed)
|
||||
#expect(context.recordedNostrEventIDs == [giftWrap.id])
|
||||
#expect(Set(context.recordedNostrEventIDs) == Set(envelopes.map(\.id)))
|
||||
#expect(context.nostrKeyMapping[convKey] == sender.publicKeyHex)
|
||||
// The primary and compatibility envelopes carry the same authenticated
|
||||
// embedded payload and must invoke message side effects only once.
|
||||
try? await Task.sleep(nanoseconds: 200_000_000)
|
||||
await drainMainQueue()
|
||||
#expect(context.handledPrivateMessages.count == 1)
|
||||
#expect(context.handledPrivateMessages.first?.senderPubkey == sender.publicKeyHex)
|
||||
#expect(context.handledPrivateMessages.first?.convKey == convKey)
|
||||
|
||||
@@ -370,15 +380,78 @@ struct ChatNostrCoordinatorContextTests {
|
||||
#expect(pm.messageID == "gm-1")
|
||||
#expect(pm.content == "psst")
|
||||
|
||||
// The same gift wrap is dropped on replay.
|
||||
coordinator.inbound.handleGiftWrap(giftWrap, id: recipient)
|
||||
// The same private envelope is dropped on replay.
|
||||
coordinator.inbound.handlePrivateEnvelope(envelopes[0], id: recipient)
|
||||
await drainMainQueue()
|
||||
#expect(context.recordedNostrEventIDs == [giftWrap.id])
|
||||
#expect(Set(context.recordedNostrEventIDs) == Set(envelopes.map(\.id)))
|
||||
#expect(context.handledPrivateMessages.count == 1)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func handleGiftWrap_panicWipeAfterSpawnDropsDecryptedResult() async throws {
|
||||
func migrationEnvelopePairs_processEachMessageAndAckOnlyOnce() async throws {
|
||||
let context = MockChatNostrContext()
|
||||
let coordinator = ChatNostrCoordinator(context: context)
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let sender = try NostrIdentity.generate()
|
||||
let messageContent = try #require(NostrEmbeddedBitChat.encodePMForNostrNoRecipient(
|
||||
content: "migration message",
|
||||
messageID: "migration-message-id",
|
||||
senderPeerID: PeerID(str: "aabbccddeeff0011")
|
||||
))
|
||||
let deliveredContent = try #require(NostrEmbeddedBitChat.encodeAckForNostrNoRecipient(
|
||||
type: .delivered,
|
||||
messageID: "migration-ack-id",
|
||||
senderPeerID: PeerID(str: "aabbccddeeff0011")
|
||||
))
|
||||
let readContent = try #require(NostrEmbeddedBitChat.encodeAckForNostrNoRecipient(
|
||||
type: .readReceipt,
|
||||
messageID: "migration-ack-id",
|
||||
senderPeerID: PeerID(str: "aabbccddeeff0011")
|
||||
))
|
||||
|
||||
var publishedIDs: [String] = []
|
||||
for content in [messageContent, deliveredContent, readContent] {
|
||||
let envelopes = try NostrProtocol.createPrivateEnvelopePublicationBatch(
|
||||
content: content,
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
)
|
||||
#expect(envelopes.count == 2)
|
||||
publishedIDs.append(contentsOf: envelopes.map(\.id))
|
||||
for envelope in envelopes {
|
||||
coordinator.inbound.handlePrivateEnvelope(envelope, id: recipient)
|
||||
}
|
||||
}
|
||||
|
||||
// Envelope unwrap runs off the main actor; wait until every published
|
||||
// event has been recorded, then let any (incorrect) twin deliveries
|
||||
// land before asserting exact side-effect counts.
|
||||
let processed = await TestHelpers.waitUntil({
|
||||
context.recordedNostrEventIDs.count == publishedIDs.count
|
||||
})
|
||||
#expect(processed)
|
||||
try? await Task.sleep(nanoseconds: 200_000_000)
|
||||
await drainMainQueue()
|
||||
|
||||
#expect(context.handledPrivateMessages.count == 1)
|
||||
#expect(context.handledDelivered.count == 1)
|
||||
#expect(context.handledReadReceipts.count == 1)
|
||||
|
||||
// A later same-format re-envelope is a delivery retry, not the
|
||||
// migration twin, so it must still reach downstream message-ID dedup
|
||||
// and acknowledgement resend logic.
|
||||
let primaryRetry = try NostrProtocol.createPrivateEnvelope(
|
||||
content: messageContent,
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
)
|
||||
coordinator.inbound.handlePrivateEnvelope(primaryRetry, id: recipient)
|
||||
let retried = await TestHelpers.waitUntil({ context.handledPrivateMessages.count == 2 })
|
||||
#expect(retried)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func handlePrivateEnvelope_panicWipeAfterSpawnDropsDecryptedResult() async throws {
|
||||
let context = MockChatNostrContext()
|
||||
let coordinator = ChatNostrCoordinator(context: context)
|
||||
|
||||
@@ -389,7 +462,7 @@ struct ChatNostrCoordinatorContextTests {
|
||||
messageID: "gm-wipe-1",
|
||||
senderPeerID: PeerID(str: "aabbccddeeff0011")
|
||||
))
|
||||
let giftWrap = try NostrProtocol.createPrivateMessage(
|
||||
let envelope = try NostrProtocol.createPrivateEnvelope(
|
||||
content: embedded,
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
@@ -398,7 +471,7 @@ struct ChatNostrCoordinatorContextTests {
|
||||
// Spawn the detached decrypt (it strongly captures the pre-wipe
|
||||
// identity), then panic-wipe in the SAME main-actor turn — guaranteed
|
||||
// to land before the task's first main-actor hop.
|
||||
coordinator.inbound.handleGiftWrap(giftWrap, id: recipient)
|
||||
coordinator.inbound.handlePrivateEnvelope(envelope, id: recipient)
|
||||
coordinator.inbound.invalidateInFlightDecrypts()
|
||||
|
||||
// Give the detached task ample time to have delivered if the wipe
|
||||
@@ -409,9 +482,9 @@ struct ChatNostrCoordinatorContextTests {
|
||||
#expect(context.handledPrivateMessages.isEmpty)
|
||||
#expect(context.recordedNostrEventIDs.isEmpty)
|
||||
|
||||
// The pipeline itself stays usable: a gift wrap spawned AFTER the
|
||||
// The pipeline itself stays usable: an envelope spawned AFTER the
|
||||
// wipe (new generation) still decrypts and delivers.
|
||||
coordinator.inbound.handleGiftWrap(giftWrap, id: recipient)
|
||||
coordinator.inbound.handlePrivateEnvelope(envelope, id: recipient)
|
||||
let delivered = await TestHelpers.waitUntil({ context.handledPrivateMessages.count == 1 })
|
||||
#expect(delivered)
|
||||
}
|
||||
@@ -424,26 +497,26 @@ struct ChatNostrCoordinatorContextTests {
|
||||
// The inbound pipeline only ever sees verified events.
|
||||
|
||||
@Test @MainActor
|
||||
func processNostrMessage_duplicateDeliveryProcessesOnce() async throws {
|
||||
func processAccountPrivateEnvelope_duplicateDeliveryProcessesOnce() async throws {
|
||||
let context = MockChatNostrContext()
|
||||
let coordinator = ChatNostrCoordinator(context: context)
|
||||
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let sender = try NostrIdentity.generate()
|
||||
context.nostrIdentity = recipient
|
||||
let giftWrap = try NostrProtocol.createPrivateMessage(
|
||||
let envelope = try NostrProtocol.createPrivateEnvelope(
|
||||
content: "verify:noop",
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
)
|
||||
|
||||
// Fan-in of the same (already verified) gift wrap from several relays
|
||||
// Fan-in of the same (already verified) envelope from several relays
|
||||
// records and processes exactly once.
|
||||
await coordinator.inbound.processNostrMessage(giftWrap)
|
||||
#expect(context.recordedNostrEventIDs == [giftWrap.id])
|
||||
await coordinator.inbound.processAccountPrivateEnvelope(envelope)
|
||||
#expect(context.recordedNostrEventIDs == [envelope.id])
|
||||
|
||||
await coordinator.inbound.processNostrMessage(giftWrap)
|
||||
#expect(context.recordedNostrEventIDs == [giftWrap.id])
|
||||
await coordinator.inbound.processAccountPrivateEnvelope(envelope)
|
||||
#expect(context.recordedNostrEventIDs == [envelope.id])
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
|
||||
@@ -176,9 +176,7 @@ 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] = []
|
||||
var geohashPrivateMessageAccepted = true
|
||||
|
||||
func routePrivateMessage(_ content: String, to peerID: PeerID, recipientNickname: String, messageID: String) {
|
||||
routedPrivateMessages.append((content, peerID, messageID))
|
||||
@@ -190,28 +188,18 @@ 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))
|
||||
}
|
||||
|
||||
func sendGeohashPrivateMessage(_ content: String, toRecipientHex recipientHex: String, from identity: NostrIdentity, messageID: String) {
|
||||
func sendGeohashPrivateMessage(
|
||||
_ content: String,
|
||||
toRecipientHex recipientHex: String,
|
||||
from identity: NostrIdentity,
|
||||
messageID: String
|
||||
) -> Bool {
|
||||
geoPrivateMessages.append((content, recipientHex, messageID))
|
||||
return geohashPrivateMessageAccepted
|
||||
}
|
||||
|
||||
func sendGeohashDeliveryAck(for messageID: String, toRecipientHex recipientHex: String, from identity: NostrIdentity) {
|
||||
@@ -298,6 +286,11 @@ private func isRead(_ status: DeliveryStatus?, by expected: String) -> Bool {
|
||||
return false
|
||||
}
|
||||
|
||||
private func isFailed(_ status: DeliveryStatus?) -> Bool {
|
||||
if case .failed = status { return true }
|
||||
return false
|
||||
}
|
||||
|
||||
private func makeFavoriteRelationship(
|
||||
noiseKey: Data,
|
||||
nostrPublicKey: String? = nil,
|
||||
@@ -389,66 +382,6 @@ 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
|
||||
@@ -492,177 +425,22 @@ struct ChatPrivateConversationCoordinatorContextTests {
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func accountDM_handsOpenShortIDConversationToStableWhenOffline() async {
|
||||
func sendGeohashDM_rejectedAdmissionNeverBecomesSent() 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
|
||||
let recipientHex = String(repeating: "33", count: 32)
|
||||
let peerID = PeerID(nostr_: recipientHex)
|
||||
context.activeChannel = .location(
|
||||
GeohashChannel(level: .city, geohash: "u4pruy")
|
||||
)
|
||||
context.nostrKeyMapping[peerID] = recipientHex
|
||||
context.geohashPrivateMessageAccepted = false
|
||||
|
||||
#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)
|
||||
}
|
||||
coordinator.sendGeohashDM("rejected", to: peerID)
|
||||
|
||||
@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)
|
||||
#expect(context.geoPrivateMessages.map(\.content) == ["rejected"])
|
||||
#expect(context.privateChats[peerID]?.count == 1)
|
||||
#expect(isFailed(context.privateChats[peerID]?.first?.deliveryStatus))
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
|
||||
@@ -79,17 +79,12 @@ 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)
|
||||
}
|
||||
@@ -350,35 +345,6 @@ 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,17 +133,11 @@ private final class MockChatTransportEventContext: ChatTransportEventContext {
|
||||
// Delivery status
|
||||
var applyMessageDeliveryStatusResult = true
|
||||
var deliveryStatusesByMessageID: [String: DeliveryStatus] = [:]
|
||||
private(set) var appliedDeliveryStatuses: [
|
||||
(messageID: String, status: DeliveryStatus, peerIDAliases: Set<PeerID>)
|
||||
] = []
|
||||
private(set) var appliedDeliveryStatuses: [(messageID: String, status: DeliveryStatus)] = []
|
||||
|
||||
@discardableResult
|
||||
func applyAcknowledgedMessageDeliveryStatus(
|
||||
_ messageID: String,
|
||||
status: DeliveryStatus,
|
||||
from peerIDAliases: Set<PeerID>
|
||||
) -> Bool {
|
||||
appliedDeliveryStatuses.append((messageID, status, peerIDAliases))
|
||||
func applyMessageDeliveryStatus(_ messageID: String, status: DeliveryStatus) -> Bool {
|
||||
appliedDeliveryStatuses.append((messageID, status))
|
||||
return applyMessageDeliveryStatusResult
|
||||
}
|
||||
|
||||
@@ -423,10 +417,6 @@ 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")
|
||||
@@ -448,8 +438,6 @@ 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,7 +98,6 @@ 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)] = []
|
||||
|
||||
@@ -119,10 +118,6 @@ 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))
|
||||
}
|
||||
@@ -274,10 +269,6 @@ 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()
|
||||
@@ -288,11 +279,9 @@ struct ChatVerificationCoordinatorContextTests {
|
||||
callbacks?.onPeerAuthenticated(peerID, "fp-verified")
|
||||
await waitForMainQueue()
|
||||
#expect(context.encryptionStatuses[peerID] == .noiseVerified)
|
||||
let stablePeerID = PeerID(hexData: noiseKey)
|
||||
#expect(context.stablePeerIDCache[peerID] == stablePeerID)
|
||||
#expect(context.stablePeerIDCache[peerID] == PeerID(hexData: noiseKey))
|
||||
#expect(context.invalidatedEncryptionCachePeers.contains(peerID))
|
||||
#expect(context.privateMediaAuthenticatedPeers == [peerID])
|
||||
#expect(context.securePrivateMessageRetryAliases == [[peerID, stablePeerID]])
|
||||
|
||||
// Handshake required -> handshaking status.
|
||||
callbacks?.onHandshakeRequired(peerID)
|
||||
|
||||
@@ -13,11 +13,8 @@ import BitFoundation
|
||||
// MARK: - Test Helpers
|
||||
|
||||
@MainActor
|
||||
private func makeTestableViewModel(
|
||||
keychain injectedKeychain: MockKeychain? = nil,
|
||||
outboxStore: MessageOutboxStore? = nil
|
||||
) -> (viewModel: ChatViewModel, transport: MockTransport) {
|
||||
let keychain = injectedKeychain ?? MockKeychain()
|
||||
private func makeTestableViewModel() -> (viewModel: ChatViewModel, transport: MockTransport) {
|
||||
let keychain = MockKeychain()
|
||||
let keychainHelper = MockKeychainHelper()
|
||||
let idBridge = NostrIdentityBridge(keychain: keychainHelper)
|
||||
let identityManager = MockIdentityManager(keychain)
|
||||
@@ -27,8 +24,7 @@ private func makeTestableViewModel(
|
||||
keychain: keychain,
|
||||
idBridge: idBridge,
|
||||
identityManager: identityManager,
|
||||
transport: transport,
|
||||
outboxStore: outboxStore
|
||||
transport: transport
|
||||
)
|
||||
|
||||
return (viewModel, transport)
|
||||
@@ -302,137 +298,6 @@ 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()
|
||||
@@ -458,65 +323,6 @@ 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
|
||||
@@ -771,27 +577,12 @@ 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)
|
||||
}
|
||||
@@ -813,28 +604,6 @@ 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
|
||||
@@ -916,163 +685,7 @@ struct ChatDeliveryCoordinatorContextTests {
|
||||
|
||||
#expect(isRead(coordinator.deliveryStatus(for: messageID)))
|
||||
#expect(context.notifyUIChangedCount == 1)
|
||||
#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)
|
||||
#expect(context.markedDeliveredMessageIDs == [messageID])
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
|
||||
@@ -373,20 +373,25 @@ struct ChatViewModelNostrExtensionTests {
|
||||
// `test_receiveGiftWrap_tamperedSignatureIsDroppedAndDoesNotPoisonDedup`.
|
||||
|
||||
@Test @MainActor
|
||||
func subscribeGiftWrap_rejectsOversizedEmbeddedPacket() async throws {
|
||||
func privateEnvelope_rejectsOversizedEmbeddedPacketBeforePublication() async throws {
|
||||
let (viewModel, _) = makeTestableViewModel()
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
|
||||
let oversized = Data(repeating: 0x41, count: FileTransferLimits.maxFramedFileBytes + 1)
|
||||
let content = "bitchat1:" + base64URLEncode(oversized)
|
||||
let giftWrap = try NostrProtocol.createPrivateMessage(
|
||||
content: content,
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
)
|
||||
|
||||
viewModel.subscribeGiftWrap(giftWrap, id: recipient)
|
||||
do {
|
||||
_ = try NostrProtocol.createPrivateEnvelope(
|
||||
content: content,
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
)
|
||||
Issue.record("Expected oversized private-envelope plaintext to be rejected")
|
||||
} catch NostrError.invalidCiphertext {
|
||||
// Rejected before encryption/publication, as intended.
|
||||
} catch {
|
||||
Issue.record("Expected NostrError.invalidCiphertext, got \(error)")
|
||||
}
|
||||
|
||||
try? await Task.sleep(nanoseconds: 100_000_000)
|
||||
#expect(viewModel.privateChats.isEmpty)
|
||||
@@ -431,7 +436,7 @@ struct ChatViewModelNostrExtensionTests {
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func subscribeGiftWrap_deliveredAckUpdatesExistingMessage() async throws {
|
||||
func subscribePrivateEnvelope_deliveredAckUpdatesExistingMessage() async throws {
|
||||
let (viewModel, _) = makeTestableViewModel()
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
@@ -453,13 +458,13 @@ struct ChatViewModelNostrExtensionTests {
|
||||
], for: convKey)
|
||||
|
||||
let content = try ackContent(type: .delivered, messageID: messageID, senderPeerID: PeerID(str: "0123456789abcdef"))
|
||||
let giftWrap = try NostrProtocol.createPrivateMessage(
|
||||
let envelope = try NostrProtocol.createPrivateEnvelope(
|
||||
content: content,
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
)
|
||||
|
||||
viewModel.subscribeGiftWrap(giftWrap, id: recipient)
|
||||
viewModel.subscribePrivateEnvelope(envelope, id: recipient)
|
||||
|
||||
let didUpdate = await TestHelpers.waitUntil(
|
||||
{ isDelivered(status: deliveryStatus(in: viewModel, peerID: convKey, messageID: messageID)) },
|
||||
@@ -469,7 +474,7 @@ struct ChatViewModelNostrExtensionTests {
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func subscribeGiftWrap_readAckUpdatesExistingMessage() async throws {
|
||||
func subscribePrivateEnvelope_readAckUpdatesExistingMessage() async throws {
|
||||
let (viewModel, _) = makeTestableViewModel()
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
@@ -491,13 +496,13 @@ struct ChatViewModelNostrExtensionTests {
|
||||
], for: convKey)
|
||||
|
||||
let content = try ackContent(type: .readReceipt, messageID: messageID, senderPeerID: PeerID(str: "0123456789abcdef"))
|
||||
let giftWrap = try NostrProtocol.createPrivateMessage(
|
||||
let envelope = try NostrProtocol.createPrivateEnvelope(
|
||||
content: content,
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
)
|
||||
|
||||
viewModel.subscribeGiftWrap(giftWrap, id: recipient)
|
||||
viewModel.subscribePrivateEnvelope(envelope, id: recipient)
|
||||
|
||||
let didUpdate = await TestHelpers.waitUntil(
|
||||
{ isRead(status: deliveryStatus(in: viewModel, peerID: convKey, messageID: messageID)) },
|
||||
@@ -507,28 +512,28 @@ struct ChatViewModelNostrExtensionTests {
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func handleGiftWrap_privateMessageStoresConversationAndMapping() async throws {
|
||||
func handlePrivateEnvelope_privateMessageStoresConversationAndMapping() async throws {
|
||||
let (viewModel, _) = makeTestableViewModel()
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let messageID = "gift-private"
|
||||
let messageID = "envelope-private"
|
||||
let convKey = PeerID(nostr_: sender.publicKeyHex)
|
||||
|
||||
let content = try privateMessageContent(
|
||||
text: "Hello from gift wrap",
|
||||
text: "Hello from private envelope",
|
||||
messageID: messageID,
|
||||
senderPeerID: PeerID(str: "0123456789abcdef")
|
||||
)
|
||||
let giftWrap = try NostrProtocol.createPrivateMessage(
|
||||
let envelope = try NostrProtocol.createPrivateEnvelope(
|
||||
content: content,
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
)
|
||||
|
||||
viewModel.handleGiftWrap(giftWrap, id: recipient)
|
||||
viewModel.handlePrivateEnvelope(envelope, id: recipient)
|
||||
|
||||
let didStore = await TestHelpers.waitUntil(
|
||||
{ viewModel.privateChats[convKey]?.first?.content == "Hello from gift wrap" },
|
||||
{ viewModel.privateChats[convKey]?.first?.content == "Hello from private envelope" },
|
||||
timeout: 5.0
|
||||
)
|
||||
#expect(didStore)
|
||||
@@ -537,11 +542,11 @@ struct ChatViewModelNostrExtensionTests {
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func handleGiftWrap_blockedSenderSkipsMessageStorage() async throws {
|
||||
func handlePrivateEnvelope_blockedSenderSkipsMessageStorage() async throws {
|
||||
let (viewModel, _) = makeTestableViewModel()
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let messageID = "gift-blocked"
|
||||
let messageID = "envelope-blocked"
|
||||
let convKey = PeerID(nostr_: sender.publicKeyHex)
|
||||
|
||||
viewModel.identityManager.setNostrBlocked(sender.publicKeyHex, isBlocked: true)
|
||||
@@ -551,13 +556,13 @@ struct ChatViewModelNostrExtensionTests {
|
||||
messageID: messageID,
|
||||
senderPeerID: PeerID(str: "0123456789abcdef")
|
||||
)
|
||||
let giftWrap = try NostrProtocol.createPrivateMessage(
|
||||
let envelope = try NostrProtocol.createPrivateEnvelope(
|
||||
content: content,
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
)
|
||||
|
||||
viewModel.handleGiftWrap(giftWrap, id: recipient)
|
||||
viewModel.handlePrivateEnvelope(envelope, id: recipient)
|
||||
|
||||
// Gift-wrap decryption runs off the main actor; wait for the ack
|
||||
// (sent even for blocked senders) to know processing finished.
|
||||
@@ -570,12 +575,12 @@ struct ChatViewModelNostrExtensionTests {
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func handleGiftWrap_deliveredAckUpdatesExistingMessage() async throws {
|
||||
func handlePrivateEnvelope_deliveredAckUpdatesExistingMessage() async throws {
|
||||
let (viewModel, _) = makeTestableViewModel()
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let convKey = PeerID(nostr_: sender.publicKeyHex)
|
||||
let messageID = "gift-delivered"
|
||||
let messageID = "envelope-delivered"
|
||||
|
||||
viewModel.seedPrivateChat([
|
||||
BitchatMessage(
|
||||
@@ -592,13 +597,13 @@ struct ChatViewModelNostrExtensionTests {
|
||||
], for: convKey)
|
||||
|
||||
let content = try ackContent(type: .delivered, messageID: messageID, senderPeerID: PeerID(str: "0123456789abcdef"))
|
||||
let giftWrap = try NostrProtocol.createPrivateMessage(
|
||||
let envelope = try NostrProtocol.createPrivateEnvelope(
|
||||
content: content,
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
)
|
||||
|
||||
viewModel.handleGiftWrap(giftWrap, id: recipient)
|
||||
viewModel.handlePrivateEnvelope(envelope, id: recipient)
|
||||
|
||||
let didUpdate = await TestHelpers.waitUntil(
|
||||
{ isDelivered(status: deliveryStatus(in: viewModel, peerID: convKey, messageID: messageID)) },
|
||||
@@ -766,6 +771,63 @@ struct ChatViewModelGeoDMTests {
|
||||
#expect(isFailed(status: viewModel.privateChats[convKey]?.last?.deliveryStatus))
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func geohashTerminalRelayFailure_transitionsSentMessageToFailed() async throws {
|
||||
let (viewModel, _) = makeTestableViewModel()
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let messageID = "geo-terminal-failure"
|
||||
let convKey = PeerID(nostr_: recipient.publicKeyHex)
|
||||
let message = BitchatMessage(
|
||||
id: messageID,
|
||||
sender: viewModel.nickname,
|
||||
content: "queued geohash message",
|
||||
timestamp: Date(),
|
||||
isRelay: false,
|
||||
isPrivate: true,
|
||||
recipientNickname: "recipient",
|
||||
senderPeerID: viewModel.myPeerID,
|
||||
deliveryStatus: .sent
|
||||
)
|
||||
viewModel.seedPrivateChat([message], for: convKey)
|
||||
|
||||
var terminalFailure: (@MainActor () -> Void)?
|
||||
let dependencies = NostrTransport.Dependencies(
|
||||
notificationCenter: NotificationCenter(),
|
||||
loadFavorites: { [:] },
|
||||
favoriteStatusForNoiseKey: { _ in nil },
|
||||
favoriteStatusForPeerID: { _ in nil },
|
||||
currentIdentity: { sender },
|
||||
registerPendingPrivateEnvelope: { _ in },
|
||||
sendPrivateEnvelopeBatch: { _, failure in
|
||||
terminalFailure = failure
|
||||
return true
|
||||
},
|
||||
scheduleAfter: { _, _ in },
|
||||
relayConnectivity: {
|
||||
Just(false).eraseToAnyPublisher()
|
||||
}
|
||||
)
|
||||
let transport = viewModel.makeGeohashNostrTransport(
|
||||
dependencies: dependencies
|
||||
)
|
||||
|
||||
let accepted = transport.sendPrivateMessageGeohash(
|
||||
content: message.content,
|
||||
toRecipientHex: recipient.publicKeyHex,
|
||||
from: sender,
|
||||
messageID: messageID
|
||||
)
|
||||
|
||||
#expect(accepted)
|
||||
#expect(viewModel.privateChats[convKey]?.first?.deliveryStatus == .sent)
|
||||
let fail = try #require(terminalFailure)
|
||||
fail()
|
||||
#expect(isFailed(
|
||||
status: viewModel.privateChats[convKey]?.first?.deliveryStatus
|
||||
))
|
||||
}
|
||||
|
||||
/// The blocked notice belongs in the DM thread the person is typing in,
|
||||
/// not on the active location-channel timeline.
|
||||
@Test @MainActor
|
||||
@@ -1374,37 +1436,3 @@ 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.settleTimeout)
|
||||
timeout: TestConstants.shortTimeout)
|
||||
#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.settleTimeout)
|
||||
timeout: TestConstants.shortTimeout)
|
||||
#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.settleTimeout)
|
||||
timeout: TestConstants.shortTimeout)
|
||||
#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.settleTimeout)
|
||||
timeout: TestConstants.shortTimeout)
|
||||
#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.settleTimeout
|
||||
timeout: TestConstants.defaultTimeout
|
||||
)
|
||||
|
||||
// Assert
|
||||
@@ -140,7 +140,7 @@ struct ChatViewModelRefactoringTests {
|
||||
{
|
||||
viewModel.publicMessages(for: .mesh).contains(where: { $0.content == "Public Hi" })
|
||||
},
|
||||
timeout: TestConstants.settleTimeout
|
||||
timeout: TestConstants.defaultTimeout
|
||||
)
|
||||
|
||||
// Assert
|
||||
|
||||
@@ -321,7 +321,7 @@ struct ChatViewModelCommandTests {
|
||||
transport.simulateConnect(peerID, nickname: "Alice")
|
||||
let resolved = await TestHelpers.waitUntil({
|
||||
viewModel.getPeerIDForNickname("Alice") == peerID
|
||||
}, timeout: TestConstants.negativeWaitWindow)
|
||||
}, timeout: TestConstants.defaultTimeout)
|
||||
#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.negativeWaitWindow)
|
||||
}, timeout: TestConstants.defaultTimeout)
|
||||
|
||||
#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.settleTimeout)
|
||||
}, timeout: TestConstants.defaultTimeout)
|
||||
|
||||
#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.settleTimeout)
|
||||
}, timeout: TestConstants.defaultTimeout)
|
||||
|
||||
let acked = await TestHelpers.waitUntil({
|
||||
transport.sentDeliveryAcks.contains { $0.messageID == "pm-noise-1" && $0.peerID == peerID }
|
||||
}, timeout: TestConstants.settleTimeout)
|
||||
}, timeout: TestConstants.defaultTimeout)
|
||||
|
||||
#expect(stored)
|
||||
#expect(acked)
|
||||
@@ -579,7 +579,7 @@ struct ChatViewModelNoisePayloadTests {
|
||||
return name == "Bob"
|
||||
}
|
||||
return false
|
||||
}, timeout: TestConstants.settleTimeout)
|
||||
}, timeout: TestConstants.defaultTimeout)
|
||||
|
||||
#expect(delivered)
|
||||
}
|
||||
@@ -617,7 +617,7 @@ struct ChatViewModelNoisePayloadTests {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}, timeout: TestConstants.settleTimeout)
|
||||
}, timeout: TestConstants.defaultTimeout)
|
||||
|
||||
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.settleTimeout)
|
||||
}, timeout: TestConstants.defaultTimeout)
|
||||
|
||||
#expect(privateChatUpdated)
|
||||
#expect(conversationStoreUpdated)
|
||||
@@ -730,7 +730,7 @@ struct ChatViewModelVerificationTests {
|
||||
|
||||
let bound = await TestHelpers.waitUntil({
|
||||
viewModel.unifiedPeerService.peers.contains { $0.peerID == peerID }
|
||||
}, timeout: TestConstants.settleTimeout)
|
||||
}, timeout: TestConstants.defaultTimeout)
|
||||
#expect(bound)
|
||||
|
||||
let qr = VerificationService.VerificationQR(
|
||||
@@ -982,7 +982,7 @@ struct ChatViewModelPeerTests {
|
||||
|
||||
let cleaned = await TestHelpers.waitUntil({
|
||||
!viewModel.unreadPrivateMessages.contains(stalePeer)
|
||||
}, timeout: TestConstants.settleTimeout)
|
||||
}, timeout: TestConstants.defaultTimeout)
|
||||
|
||||
#expect(cleaned)
|
||||
}
|
||||
|
||||
@@ -1179,71 +1179,6 @@ 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.settleTimeout
|
||||
timeout: TestConstants.defaultTimeout
|
||||
)
|
||||
#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.settleTimeout
|
||||
timeout: TestConstants.defaultTimeout
|
||||
)
|
||||
#expect(carried)
|
||||
|
||||
@@ -161,7 +161,7 @@ struct CourierEndToEndTests {
|
||||
bob.sendBroadcastAnnounce()
|
||||
let announced = await TestHelpers.waitUntil(
|
||||
{ bobOut.first(ofType: .announce) != nil },
|
||||
timeout: TestConstants.settleTimeout
|
||||
timeout: TestConstants.defaultTimeout
|
||||
)
|
||||
#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.negativeWaitWindow
|
||||
timeout: TestConstants.defaultTimeout
|
||||
)
|
||||
#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.settleTimeout
|
||||
timeout: TestConstants.defaultTimeout
|
||||
)
|
||||
#expect(received)
|
||||
|
||||
@@ -229,7 +229,7 @@ struct CourierEndToEndTests {
|
||||
))
|
||||
let deposited = await TestHelpers.waitUntil(
|
||||
{ aliceOut.first(ofType: .courierEnvelope) != nil },
|
||||
timeout: TestConstants.settleTimeout
|
||||
timeout: TestConstants.defaultTimeout
|
||||
)
|
||||
#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.settleTimeout
|
||||
timeout: TestConstants.defaultTimeout
|
||||
)
|
||||
#expect(carried)
|
||||
|
||||
@@ -245,7 +245,7 @@ struct CourierEndToEndTests {
|
||||
bob.sendBroadcastAnnounce()
|
||||
let announced = await TestHelpers.waitUntil(
|
||||
{ bobOut.first(ofType: .announce) != nil },
|
||||
timeout: TestConstants.settleTimeout
|
||||
timeout: TestConstants.defaultTimeout
|
||||
)
|
||||
#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.settleTimeout
|
||||
timeout: TestConstants.defaultTimeout
|
||||
)
|
||||
#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.negativeWaitWindow
|
||||
timeout: TestConstants.shortTimeout
|
||||
)
|
||||
#expect(!delivered)
|
||||
}
|
||||
@@ -293,7 +293,7 @@ struct CourierEndToEndTests {
|
||||
))
|
||||
let deposited = await TestHelpers.waitUntil(
|
||||
{ aliceOut.first(ofType: .courierEnvelope) != nil },
|
||||
timeout: TestConstants.settleTimeout
|
||||
timeout: TestConstants.defaultTimeout
|
||||
)
|
||||
#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.settleTimeout
|
||||
timeout: TestConstants.defaultTimeout
|
||||
)
|
||||
#expect(carried)
|
||||
|
||||
@@ -310,7 +310,7 @@ struct CourierEndToEndTests {
|
||||
|
||||
let leakedOnUnverifiedAnnounce = await TestHelpers.waitUntil(
|
||||
{ carolOut.count(ofType: .courierEnvelope) > 0 },
|
||||
timeout: TestConstants.negativeWaitWindow
|
||||
timeout: TestConstants.shortTimeout
|
||||
)
|
||||
#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.negativeWaitWindow
|
||||
timeout: TestConstants.defaultTimeout
|
||||
)
|
||||
#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.negativeWaitWindow
|
||||
timeout: TestConstants.defaultTimeout
|
||||
)
|
||||
#expect(handedOver)
|
||||
#expect(!carol.courierStore.isEmpty)
|
||||
@@ -355,7 +355,7 @@ struct CourierEndToEndTests {
|
||||
))
|
||||
let deposited = await TestHelpers.waitUntil(
|
||||
{ aliceOut.first(ofType: .courierEnvelope) != nil },
|
||||
timeout: TestConstants.settleTimeout
|
||||
timeout: TestConstants.defaultTimeout
|
||||
)
|
||||
#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.settleTimeout
|
||||
timeout: TestConstants.defaultTimeout
|
||||
)
|
||||
#expect(carried)
|
||||
|
||||
bob.sendBroadcastAnnounce()
|
||||
let announced = await TestHelpers.waitUntil(
|
||||
{ bobOut.first(ofType: .announce) != nil },
|
||||
timeout: TestConstants.settleTimeout
|
||||
timeout: TestConstants.defaultTimeout
|
||||
)
|
||||
#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.negativeWaitWindow
|
||||
timeout: TestConstants.defaultTimeout
|
||||
)
|
||||
#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.settleTimeout
|
||||
timeout: TestConstants.defaultTimeout
|
||||
)
|
||||
#expect(reannounced)
|
||||
let freshAnnounce = try #require(
|
||||
@@ -410,7 +410,7 @@ struct CourierEndToEndTests {
|
||||
|
||||
let refloodedInCooldown = await TestHelpers.waitUntil(
|
||||
{ carolOut.count(ofType: .courierEnvelope) > 1 },
|
||||
timeout: TestConstants.negativeWaitWindow
|
||||
timeout: TestConstants.shortTimeout
|
||||
)
|
||||
#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.settleTimeout
|
||||
timeout: TestConstants.defaultTimeout
|
||||
)
|
||||
#expect(announcedAgain)
|
||||
let directAgain = try #require(
|
||||
@@ -434,7 +434,7 @@ struct CourierEndToEndTests {
|
||||
|
||||
let handedOverWithoutLinkProof = await TestHelpers.waitUntil(
|
||||
{ carolOut.count(ofType: .courierEnvelope) > 1 },
|
||||
timeout: TestConstants.negativeWaitWindow
|
||||
timeout: TestConstants.shortTimeout
|
||||
)
|
||||
#expect(!handedOverWithoutLinkProof)
|
||||
#expect(!carol.courierStore.isEmpty)
|
||||
@@ -457,7 +457,7 @@ struct CourierEndToEndTests {
|
||||
|
||||
let queuedPacket = await TestHelpers.waitUntil(
|
||||
{ aliceOut.first(ofType: .courierEnvelope) != nil },
|
||||
timeout: TestConstants.negativeWaitWindow
|
||||
timeout: TestConstants.shortTimeout
|
||||
)
|
||||
#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.negativeWaitWindow
|
||||
timeout: TestConstants.shortTimeout
|
||||
)
|
||||
#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.negativeWaitWindow
|
||||
timeout: TestConstants.shortTimeout
|
||||
)
|
||||
#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.negativeWaitWindow
|
||||
timeout: TestConstants.shortTimeout
|
||||
)
|
||||
#expect(!stored)
|
||||
}
|
||||
@@ -602,14 +602,14 @@ struct CourierEndToEndTests {
|
||||
|
||||
let delivered = await TestHelpers.waitUntil(
|
||||
{ !bobDelegate.snapshot().isEmpty },
|
||||
timeout: TestConstants.settleTimeout
|
||||
timeout: TestConstants.defaultTimeout
|
||||
)
|
||||
#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.negativeWaitWindow
|
||||
timeout: TestConstants.shortTimeout
|
||||
)
|
||||
#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.negativeWaitWindow
|
||||
timeout: TestConstants.shortTimeout
|
||||
)
|
||||
#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.settleTimeout
|
||||
timeout: TestConstants.defaultTimeout
|
||||
)
|
||||
#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.settleTimeout
|
||||
timeout: TestConstants.defaultTimeout
|
||||
)
|
||||
#expect(published)
|
||||
return (
|
||||
@@ -124,7 +124,7 @@ struct PrekeyEndToEndTests {
|
||||
|
||||
let cached = await TestHelpers.waitUntil(
|
||||
{ alice.prekeyBundleStore.hasUsableBundle(for: bob.noiseStaticPublicKeyData()) },
|
||||
timeout: TestConstants.settleTimeout
|
||||
timeout: TestConstants.defaultTimeout
|
||||
)
|
||||
#expect(cached)
|
||||
|
||||
@@ -138,7 +138,7 @@ struct PrekeyEndToEndTests {
|
||||
))
|
||||
let deposited = await TestHelpers.waitUntil(
|
||||
{ aliceOut.first(ofType: .courierEnvelope) != nil },
|
||||
timeout: TestConstants.settleTimeout
|
||||
timeout: TestConstants.defaultTimeout
|
||||
)
|
||||
#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.settleTimeout
|
||||
timeout: TestConstants.defaultTimeout
|
||||
)
|
||||
#expect(carried)
|
||||
|
||||
@@ -158,7 +158,7 @@ struct PrekeyEndToEndTests {
|
||||
bob.sendBroadcastAnnounce()
|
||||
let reannounced = await TestHelpers.waitUntil(
|
||||
{ bobOut.first(ofType: .announce) != nil },
|
||||
timeout: TestConstants.settleTimeout
|
||||
timeout: TestConstants.defaultTimeout
|
||||
)
|
||||
#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.settleTimeout
|
||||
timeout: TestConstants.defaultTimeout
|
||||
)
|
||||
#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.settleTimeout
|
||||
timeout: TestConstants.defaultTimeout
|
||||
)
|
||||
#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.negativeWaitWindow
|
||||
timeout: TestConstants.shortTimeout
|
||||
)
|
||||
#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.settleTimeout
|
||||
timeout: TestConstants.defaultTimeout
|
||||
)
|
||||
#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.settleTimeout
|
||||
timeout: TestConstants.defaultTimeout
|
||||
)
|
||||
#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.negativeWaitWindow
|
||||
timeout: TestConstants.shortTimeout
|
||||
)
|
||||
#expect(!cached)
|
||||
}
|
||||
@@ -310,7 +310,7 @@ struct PrekeyEndToEndTests {
|
||||
|
||||
let cached = await TestHelpers.waitUntil(
|
||||
{ alice.prekeyBundleStore.hasUsableBundle(for: bob.noiseStaticPublicKeyData()) },
|
||||
timeout: TestConstants.negativeWaitWindow
|
||||
timeout: TestConstants.shortTimeout
|
||||
)
|
||||
#expect(!cached)
|
||||
}
|
||||
@@ -328,7 +328,7 @@ struct PrekeyEndToEndTests {
|
||||
|
||||
let cached = await TestHelpers.waitUntil(
|
||||
{ alice.prekeyBundleStore.hasUsableBundle(for: bob.noiseStaticPublicKeyData()) },
|
||||
timeout: TestConstants.settleTimeout
|
||||
timeout: TestConstants.defaultTimeout
|
||||
)
|
||||
#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.negativeWaitWindow
|
||||
timeout: TestConstants.shortTimeout
|
||||
)
|
||||
#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.negativeWaitWindow
|
||||
timeout: TestConstants.shortTimeout
|
||||
)
|
||||
#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.settleTimeout)
|
||||
try await TestHelpers.waitFor({ delegate.lastPacket != nil }, timeout: TestConstants.shortTimeout)
|
||||
}
|
||||
|
||||
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.settleTimeout)
|
||||
try await TestHelpers.waitFor({ delegate.packets.count == 2 }, timeout: TestConstants.shortTimeout)
|
||||
// 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.settleTimeout)
|
||||
try await TestHelpers.waitFor({ delegate.packets.count >= 1 }, timeout: TestConstants.shortTimeout)
|
||||
// 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.settleTimeout)
|
||||
try await TestHelpers.waitFor({ delegate.packets.count == 1 }, timeout: TestConstants.shortTimeout)
|
||||
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.settleTimeout)
|
||||
try await TestHelpers.waitFor({ delegate.packets.count == 1 }, timeout: TestConstants.shortTimeout)
|
||||
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.settleTimeout)
|
||||
try await TestHelpers.waitFor({ delegate.packets.count == 1 }, timeout: TestConstants.shortTimeout)
|
||||
// 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.settleTimeout)
|
||||
try await TestHelpers.waitFor({ delegate.packets.count == 1 }, timeout: TestConstants.shortTimeout)
|
||||
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.settleTimeout)
|
||||
try await TestHelpers.waitFor({ delegate.packets.count == 1 }, timeout: TestConstants.shortTimeout)
|
||||
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.settleTimeout
|
||||
timeout: TestConstants.shortTimeout
|
||||
)
|
||||
#expect(restored)
|
||||
}
|
||||
@@ -810,45 +810,6 @@ 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,15 +65,11 @@ 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
|
||||
@@ -178,11 +174,6 @@ 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) {
|
||||
@@ -224,12 +215,6 @@ 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 = TestConstants.settleTimeout,
|
||||
timeout: TimeInterval = 1.0,
|
||||
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: TestConstants.settleTimeout)
|
||||
_ = decryptResult.wait(timeout: 5)
|
||||
if let promotionResultForCleanup {
|
||||
_ = promotionResultForCleanup.wait(timeout: TestConstants.settleTimeout)
|
||||
_ = promotionResultForCleanup.wait(timeout: 5)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -751,19 +751,15 @@ struct NoiseCoverageTests {
|
||||
promotionThread.name = "NoiseCoverageTests.staleDecrypt.promote"
|
||||
promotionThread.qualityOfService = .userInitiated
|
||||
promotionThread.start()
|
||||
try #require(promotionStarted.wait(timeout: .now() + TestConstants.settleTimeout) == .success)
|
||||
try #require(promotionStarted.wait(timeout: .now() + 5) == .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: TestConstants.settleTimeout)).get()
|
||||
_ = try #require(promotionResult.wait(timeout: TestConstants.settleTimeout)).get()
|
||||
let decrypted = try #require(decryptResult.wait(timeout: 5)).get()
|
||||
_ = try #require(promotionResult.wait(timeout: 5)).get()
|
||||
|
||||
#expect(decrypted.plaintext == Data("old session".utf8))
|
||||
#expect(decrypted.sessionGeneration == oldGeneration)
|
||||
|
||||
@@ -580,16 +580,8 @@ 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 = TestConstants.settleTimeout,
|
||||
timeout: TimeInterval = 10.0,
|
||||
condition: @escaping @MainActor () async -> Bool
|
||||
) async -> Bool {
|
||||
let deadline = Date().addingTimeInterval(timeout)
|
||||
|
||||
@@ -1,130 +0,0 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,7 @@ import BitFoundation
|
||||
|
||||
struct NostrProtocolTests {
|
||||
|
||||
@Test func nip17MessageRoundTrip() throws {
|
||||
@Test func privateEnvelopeRoundTrip() throws {
|
||||
// Create sender and recipient identities
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
@@ -21,21 +21,19 @@ struct NostrProtocolTests {
|
||||
print("Recipient pubkey: \(recipient.publicKeyHex)")
|
||||
|
||||
// Create a test message
|
||||
let originalContent = "Hello from NIP-17 test!"
|
||||
let originalContent = "Hello from BitChat private-envelope test!"
|
||||
|
||||
// Create encrypted gift wrap
|
||||
let giftWrap = try NostrProtocol.createPrivateMessage(
|
||||
let envelope = try NostrProtocol.createPrivateEnvelope(
|
||||
content: originalContent,
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
)
|
||||
|
||||
print("Gift wrap created with ID: \(giftWrap.id)")
|
||||
print("Gift wrap pubkey: \(giftWrap.pubkey)")
|
||||
print("Private envelope created with ID: \(envelope.id)")
|
||||
print("Private envelope pubkey: \(envelope.pubkey)")
|
||||
|
||||
// Decrypt the gift wrap
|
||||
let (decryptedContent, senderPubkey, timestamp) = try NostrProtocol.decryptPrivateMessage(
|
||||
giftWrap: giftWrap,
|
||||
let (decryptedContent, senderPubkey, timestamp) = try NostrProtocol.decryptPrivateEnvelope(
|
||||
envelope: envelope,
|
||||
recipientIdentity: recipient
|
||||
)
|
||||
|
||||
@@ -51,117 +49,130 @@ struct NostrProtocolTests {
|
||||
print("✅ Successfully decrypted message: '\(decryptedContent)' from \(senderPubkey) at \(messageDate)")
|
||||
}
|
||||
|
||||
@Test func giftWrapUsesUniqueEphemeralKeys() throws {
|
||||
@Test func privateEnvelopesUseUniqueEphemeralKeys() throws {
|
||||
// Create identities
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
|
||||
// Create two messages
|
||||
let message1 = try NostrProtocol.createPrivateMessage(
|
||||
let message1 = try NostrProtocol.createPrivateEnvelope(
|
||||
content: "Message 1",
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
)
|
||||
|
||||
let message2 = try NostrProtocol.createPrivateMessage(
|
||||
let message2 = try NostrProtocol.createPrivateEnvelope(
|
||||
content: "Message 2",
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
)
|
||||
|
||||
// Gift wrap pubkeys should be different (unique ephemeral keys)
|
||||
// Public envelope keys must be one-time use.
|
||||
#expect(message1.pubkey != message2.pubkey)
|
||||
|
||||
print("Message 1 gift wrap pubkey: \(message1.pubkey)")
|
||||
print("Message 2 gift wrap pubkey: \(message2.pubkey)")
|
||||
print("Message 1 envelope pubkey: \(message1.pubkey)")
|
||||
print("Message 2 envelope pubkey: \(message2.pubkey)")
|
||||
|
||||
// Both should decrypt successfully
|
||||
let (content1, _, _) = try NostrProtocol.decryptPrivateMessage(
|
||||
giftWrap: message1,
|
||||
let (content1, _, _) = try NostrProtocol.decryptPrivateEnvelope(
|
||||
envelope: message1,
|
||||
recipientIdentity: recipient
|
||||
)
|
||||
let (content2, _, _) = try NostrProtocol.decryptPrivateMessage(
|
||||
giftWrap: message2,
|
||||
let (content2, _, _) = try NostrProtocol.decryptPrivateEnvelope(
|
||||
envelope: message2,
|
||||
recipientIdentity: recipient
|
||||
)
|
||||
|
||||
#expect(content1 == "Message 1")
|
||||
#expect(content2 == "Message 2")
|
||||
}
|
||||
|
||||
@Test func decryptionFailsWithWrongRecipient() throws {
|
||||
|
||||
@Test func privateEnvelopeUsesBitChatWireFormatAtEveryLayer() throws {
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let wrongRecipient = try NostrIdentity.generate()
|
||||
|
||||
// Create message for recipient
|
||||
let giftWrap = try NostrProtocol.createPrivateMessage(
|
||||
content: "Secret message",
|
||||
let envelope = try NostrProtocol.createPrivateEnvelope(
|
||||
content: "bitchat-specific",
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
)
|
||||
|
||||
// Try to decrypt with wrong recipient. The outer envelope is bound to
|
||||
// the addressed recipient's `p` tag, so this now fails validation
|
||||
// before any decryption is attempted.
|
||||
expectInvalidEvent {
|
||||
_ = try NostrProtocol.decryptPrivateMessage(
|
||||
giftWrap: giftWrap,
|
||||
recipientIdentity: wrongRecipient
|
||||
)
|
||||
}
|
||||
|
||||
#expect(envelope.kind == NostrProtocol.EventKind.privateEnvelope.rawValue)
|
||||
#expect(envelope.kind != NostrProtocol.EventKind.legacyNIP59GiftWrap.rawValue)
|
||||
#expect(envelope.content.hasPrefix(NostrProtocol.privateEnvelopeContentPrefix))
|
||||
#expect(!envelope.content.hasPrefix("v2:"))
|
||||
#expect(envelope.tags == [["p", recipient.publicKeyHex]])
|
||||
#expect(envelope.created_at <= Int(Date().timeIntervalSince1970))
|
||||
|
||||
let layers = try NostrProtocol.decodePrivateEnvelopeLayersForTesting(
|
||||
envelope: envelope,
|
||||
recipientIdentity: recipient
|
||||
)
|
||||
#expect(layers.seal.kind == NostrProtocol.EventKind.privateSeal.rawValue)
|
||||
#expect(layers.seal.content.hasPrefix(NostrProtocol.privateEnvelopeContentPrefix))
|
||||
#expect(layers.seal.tags.isEmpty)
|
||||
#expect(layers.message.kind == NostrProtocol.EventKind.privateMessage.rawValue)
|
||||
#expect(layers.message.tags.isEmpty)
|
||||
#expect(layers.message.sig == nil)
|
||||
}
|
||||
|
||||
@Test func decryptAcceptsCurrentAndroidInnerRecipientTag() throws {
|
||||
@Test func decryptAcceptsReceiveOnlyLegacyBitChatEnvelope() throws {
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let envelope = try NostrProtocol.createLegacyPrivateEnvelopeForTesting(
|
||||
content: "legacy in-flight message",
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
)
|
||||
|
||||
#expect(envelope.kind == NostrProtocol.EventKind.legacyNIP59GiftWrap.rawValue)
|
||||
#expect(envelope.content.hasPrefix("v2:"))
|
||||
|
||||
let result = try NostrProtocol.decryptPrivateEnvelope(
|
||||
envelope: envelope,
|
||||
recipientIdentity: recipient
|
||||
)
|
||||
#expect(result.content == "legacy in-flight message")
|
||||
#expect(result.senderPubkey == sender.publicKeyHex)
|
||||
|
||||
let layers = try NostrProtocol.decodePrivateEnvelopeLayersForTesting(
|
||||
envelope: envelope,
|
||||
recipientIdentity: recipient
|
||||
)
|
||||
#expect(layers.seal.kind == NostrProtocol.EventKind.legacyNIP59Seal.rawValue)
|
||||
#expect(layers.message.kind == NostrProtocol.EventKind.legacyNIP17DirectMessage.rawValue)
|
||||
#expect(layers.message.tags.isEmpty)
|
||||
}
|
||||
|
||||
@Test func decryptAcceptsCurrentAndroidLegacyInnerRecipientTag() throws {
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
|
||||
// Current Android's `createPrivateMessage` emits an unsigned kind-14
|
||||
// inner event with exactly [["p", recipient]], while released iOS
|
||||
// uses no inner tags. This isolated generator reproduces the Android
|
||||
// wire shape without making the production encoder depend on it.
|
||||
let giftWrap = try NostrProtocol.createPrivateMessageWithInnerTagsForTesting(
|
||||
// inner event with exactly [["p", recipient]], while its outer/seal
|
||||
// layers use the deployed BitChat legacy v2 crypto. This isolated
|
||||
// generator reproduces that cross-platform wire shape without making
|
||||
// the production encoder depend on Android's historical tag choice.
|
||||
let envelope = try NostrProtocol.createLegacyPrivateEnvelopeForTesting(
|
||||
content: "legacy message from Android",
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender,
|
||||
innerMessageTags: [["p", recipient.publicKeyHex]]
|
||||
)
|
||||
|
||||
let result = try NostrProtocol.decryptPrivateMessage(
|
||||
giftWrap: giftWrap,
|
||||
let layers = try NostrProtocol.decodePrivateEnvelopeLayersForTesting(
|
||||
envelope: envelope,
|
||||
recipientIdentity: recipient
|
||||
)
|
||||
#expect(layers.message.tags == [["p", recipient.publicKeyHex]])
|
||||
|
||||
let result = try NostrProtocol.decryptPrivateEnvelope(
|
||||
envelope: envelope,
|
||||
recipientIdentity: recipient
|
||||
)
|
||||
#expect(result.content == "legacy message from Android")
|
||||
#expect(result.senderPubkey == sender.publicKeyHex)
|
||||
}
|
||||
|
||||
@Test func decryptRejectsAlternateInnerTagShapes() throws {
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let otherRecipient = try NostrIdentity.generate()
|
||||
let invalidTagShapes = [
|
||||
[["p", otherRecipient.publicKeyHex]],
|
||||
[["p", recipient.publicKeyHex], ["p", recipient.publicKeyHex]],
|
||||
[["p", recipient.publicKeyHex, "unexpected"]],
|
||||
[["x", recipient.publicKeyHex]]
|
||||
]
|
||||
|
||||
for tags in invalidTagShapes {
|
||||
let giftWrap = try NostrProtocol.createPrivateMessageWithInnerTagsForTesting(
|
||||
content: "invalid inner tag shape",
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender,
|
||||
innerMessageTags: tags
|
||||
)
|
||||
expectInvalidEvent {
|
||||
_ = try NostrProtocol.decryptPrivateMessage(
|
||||
giftWrap: giftWrap,
|
||||
recipientIdentity: recipient
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test func decryptsFrozenLegacyEnvelopeProducedByAndroidB7f0b33d() throws {
|
||||
let eventData = try Data(contentsOf: fixtureURL(
|
||||
name: "AndroidLegacyPrivateEnvelopeB7f0b33d"
|
||||
@@ -190,19 +201,68 @@ struct NostrProtocolTests {
|
||||
#expect(generatorPatch.contains("fun emitCrossPlatformFixtures()"))
|
||||
#expect(generatorPatch.contains(metadata.recipientPrivateKey))
|
||||
#expect(envelope.isValidSignature())
|
||||
#expect(envelope.kind == NostrProtocol.EventKind.giftWrap.rawValue)
|
||||
#expect(envelope.kind == NostrProtocol.EventKind.legacyNIP59GiftWrap.rawValue)
|
||||
#expect(envelope.tags == [["p", recipient.publicKeyHex]])
|
||||
|
||||
// The Android inner event carries exactly the recipient `p` tag, so a
|
||||
// successful decrypt also proves the Android inner-tag acceptance.
|
||||
let result = try NostrProtocol.decryptPrivateMessage(
|
||||
giftWrap: envelope,
|
||||
let layers = try NostrProtocol.decodePrivateEnvelopeLayersForTesting(
|
||||
envelope: envelope,
|
||||
recipientIdentity: recipient
|
||||
)
|
||||
#expect(layers.message.tags == [["p", recipient.publicKeyHex]])
|
||||
|
||||
let result = try NostrProtocol.decryptPrivateEnvelope(
|
||||
envelope: envelope,
|
||||
recipientIdentity: recipient
|
||||
)
|
||||
#expect(result.content == "legacy fixture from Android b7f0b33d")
|
||||
#expect(result.senderPubkey == metadata.senderPublicKey)
|
||||
}
|
||||
|
||||
@Test func decryptRejectsAlternateLegacyInnerTags() throws {
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let otherRecipient = try NostrIdentity.generate()
|
||||
let invalidTagShapes = [
|
||||
[["p", otherRecipient.publicKeyHex]],
|
||||
[["p", recipient.publicKeyHex], ["p", recipient.publicKeyHex]],
|
||||
[["p", recipient.publicKeyHex, "unexpected"]],
|
||||
[["x", recipient.publicKeyHex]]
|
||||
]
|
||||
|
||||
for tags in invalidTagShapes {
|
||||
let envelope = try NostrProtocol.createLegacyPrivateEnvelopeForTesting(
|
||||
content: "invalid Android-shaped tags",
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender,
|
||||
innerMessageTags: tags
|
||||
)
|
||||
expectInvalidEvent {
|
||||
_ = try NostrProtocol.decryptPrivateEnvelope(
|
||||
envelope: envelope,
|
||||
recipientIdentity: recipient
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test func newPrivateEnvelopeRejectsInnerRecipientTag() throws {
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let envelope = try NostrProtocol.createPrivateEnvelopeWithInnerTagsForTesting(
|
||||
content: "new format stays strict",
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender,
|
||||
innerMessageTags: [["p", recipient.publicKeyHex]]
|
||||
)
|
||||
|
||||
expectInvalidEvent {
|
||||
_ = try NostrProtocol.decryptPrivateEnvelope(
|
||||
envelope: envelope,
|
||||
recipientIdentity: recipient
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func decryptsFrozenLegacyEnvelopeProducedByRelease733098bb() throws {
|
||||
let eventData = try Data(contentsOf: fixtureURL(
|
||||
name: "LegacyPrivateEnvelope733098bb"
|
||||
@@ -216,18 +276,121 @@ struct NostrProtocolTests {
|
||||
let recipient = try NostrIdentity(privateKeyData: recipientKey)
|
||||
|
||||
#expect(envelope.isValidSignature())
|
||||
let result = try NostrProtocol.decryptPrivateMessage(
|
||||
giftWrap: envelope,
|
||||
let result = try NostrProtocol.decryptPrivateEnvelope(
|
||||
envelope: envelope,
|
||||
recipientIdentity: recipient
|
||||
)
|
||||
#expect(result.content == "legacy fixture from 733098bb")
|
||||
#expect(result.senderPubkey == "2e3d79df7047204f02b726c574e256f8de1dd80510f7dcb8b0d12df13acb87e6")
|
||||
}
|
||||
|
||||
@Test func decryptRejectsOversizedCiphertextBeforeDecoding() throws {
|
||||
@Test func decryptRejectsWrongOuterKind() throws {
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let envelope = try NostrProtocol.createPrivateEnvelope(
|
||||
content: "wrong outer kind",
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
)
|
||||
// Re-mint the ciphertext under a kind that is not an accepted
|
||||
// private-envelope kind; format resolution must reject it before any
|
||||
// decryption work.
|
||||
let reminted = NostrEvent(
|
||||
pubkey: envelope.pubkey,
|
||||
createdAt: Date(timeIntervalSince1970: TimeInterval(envelope.created_at)),
|
||||
kind: .textNote,
|
||||
tags: envelope.tags,
|
||||
content: envelope.content
|
||||
)
|
||||
|
||||
expectInvalidEvent {
|
||||
_ = try NostrProtocol.decryptPrivateEnvelope(
|
||||
envelope: reminted,
|
||||
recipientIdentity: recipient
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func publicationBatchAlwaysDualPublishesForCoordinatedMigration() throws {
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
|
||||
let migrationBatch = try NostrProtocol.createPrivateEnvelopePublicationBatch(
|
||||
content: "mixed-version",
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
)
|
||||
#expect(migrationBatch.map(\.kind) == [
|
||||
NostrProtocol.EventKind.privateEnvelope.rawValue,
|
||||
NostrProtocol.EventKind.legacyNIP59GiftWrap.rawValue
|
||||
])
|
||||
for envelope in migrationBatch {
|
||||
let result = try NostrProtocol.decryptPrivateEnvelope(
|
||||
envelope: envelope,
|
||||
recipientIdentity: recipient
|
||||
)
|
||||
#expect(result.content == "mixed-version")
|
||||
}
|
||||
|
||||
// The compatibility copy retains the exact released-iOS legacy shape,
|
||||
// which current Android also accepts: kinds 1059/13/14, v2 prefix, and
|
||||
// no inner tags. There is no wall-clock branch that can silently stop
|
||||
// old-client delivery.
|
||||
let compatibilityLayers = try NostrProtocol.decodePrivateEnvelopeLayersForTesting(
|
||||
envelope: migrationBatch[1],
|
||||
recipientIdentity: recipient
|
||||
)
|
||||
#expect(migrationBatch[1].content.hasPrefix("v2:"))
|
||||
#expect(compatibilityLayers.seal.kind == NostrProtocol.EventKind.legacyNIP59Seal.rawValue)
|
||||
#expect(compatibilityLayers.message.kind == NostrProtocol.EventKind.legacyNIP17DirectMessage.rawValue)
|
||||
#expect(compatibilityLayers.message.tags.isEmpty)
|
||||
}
|
||||
|
||||
@Test func mailboxLookbackCoversDeliveryWindowAndroidFuzzAndClockSkew() {
|
||||
let sentAt = Date(timeIntervalSince1970: 1_800_000_000)
|
||||
let earliestAndroidTimestamp = sentAt.addingTimeInterval(
|
||||
-TransportConfig.nostrLegacyAndroidTimestampFuzzSeconds
|
||||
)
|
||||
let subscribeAtDeliveryBoundary = sentAt.addingTimeInterval(
|
||||
TransportConfig.nostrPrivateEnvelopeDeliveryWindowSeconds
|
||||
)
|
||||
let filterSince = subscribeAtDeliveryBoundary.addingTimeInterval(
|
||||
-TransportConfig.nostrDMSubscribeLookbackSeconds
|
||||
)
|
||||
|
||||
#expect(TransportConfig.nostrPrivateEnvelopeDeliveryWindowSeconds == 24 * 60 * 60)
|
||||
#expect(TransportConfig.nostrLegacyAndroidTimestampFuzzSeconds == 48 * 60 * 60)
|
||||
#expect(TransportConfig.nostrDMSubscribeClockSkewSeconds == 15 * 60)
|
||||
let expectedLookback: TimeInterval = 72 * 60 * 60 + 15 * 60
|
||||
#expect(TransportConfig.nostrDMSubscribeLookbackSeconds == expectedLookback)
|
||||
#expect(filterSince == earliestAndroidTimestamp.addingTimeInterval(-(15 * 60)))
|
||||
}
|
||||
|
||||
@Test func largePrivateEnvelopeFitsLayerSpecificExpansionLimits() throws {
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
// Large enough that the nested Base64 seal exceeds the inner 32 KiB
|
||||
// cap, while the inner message JSON itself remains below that cap.
|
||||
let content = String(repeating: "A", count: 30 * 1024)
|
||||
|
||||
let envelope = try NostrProtocol.createPrivateEnvelope(
|
||||
content: content,
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
)
|
||||
let decrypted = try NostrProtocol.decryptPrivateEnvelope(
|
||||
envelope: envelope,
|
||||
recipientIdentity: recipient
|
||||
)
|
||||
|
||||
#expect(decrypted.content == content)
|
||||
#expect(envelope.content.utf8.count <= NostrProtocol.maximumPrivateEnvelopeCiphertextBytes)
|
||||
}
|
||||
|
||||
@Test func privateEnvelopeRejectsOversizedCiphertextBeforeDecoding() throws {
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let wrapper = try NostrIdentity.generate()
|
||||
let oversizedContent = "v2:"
|
||||
let oversizedContent = NostrProtocol.privateEnvelopeContentPrefix
|
||||
+ String(
|
||||
repeating: "A",
|
||||
count: NostrProtocol.maximumPrivateEnvelopeCiphertextBytes
|
||||
@@ -235,21 +398,69 @@ struct NostrProtocolTests {
|
||||
let event = NostrEvent(
|
||||
pubkey: wrapper.publicKeyHex,
|
||||
createdAt: Date(),
|
||||
kind: .giftWrap,
|
||||
kind: .privateEnvelope,
|
||||
tags: [["p", recipient.publicKeyHex]],
|
||||
content: oversizedContent
|
||||
)
|
||||
let signed = try event.sign(with: wrapper.schnorrSigningKey())
|
||||
|
||||
expectInvalidCiphertext {
|
||||
_ = try NostrProtocol.decryptPrivateMessage(
|
||||
giftWrap: signed,
|
||||
_ = try NostrProtocol.decryptPrivateEnvelope(
|
||||
envelope: signed,
|
||||
recipientIdentity: recipient
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func decryptDoesNotMisinterpretStandardNIP44Payload() throws {
|
||||
@Test func privateEnvelopeRejectsOversizedPlaintextBeforeEncryption() throws {
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let oversizedPlaintext = String(
|
||||
repeating: "x",
|
||||
count: NostrProtocol.maximumPrivateEnvelopePlaintextBytes + 1
|
||||
)
|
||||
|
||||
expectInvalidCiphertext {
|
||||
_ = try NostrProtocol.createPrivateEnvelope(
|
||||
content: oversizedPlaintext,
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func privateEnvelopePublicationBatchRejectsMaximumComposerPayload() throws {
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let composerMaximum = String(
|
||||
repeating: "x",
|
||||
count: InputValidator.Limits.maxMessageLength
|
||||
)
|
||||
|
||||
#expect(
|
||||
composerMaximum.utf8.count
|
||||
> NostrProtocol.maximumPrivateEnvelopePlaintextBytes
|
||||
)
|
||||
expectInvalidCiphertext {
|
||||
_ = try NostrProtocol.createPrivateEnvelopePublicationBatch(
|
||||
content: composerMaximum,
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func privateEnvelopeRejectsOversizedNestedJSONBeforeParsing() {
|
||||
let oversizedJSON = String(
|
||||
repeating: "{",
|
||||
count: NostrProtocol.maximumPrivateEnvelopePlaintextBytes + 1
|
||||
)
|
||||
expectInvalidCiphertext {
|
||||
_ = try NostrProtocol.decodePrivateEnvelopeEventJSONForTesting(oversizedJSON)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func decryptDoesNotMisinterpretStandardNIP44PayloadAsLegacyBitChat() throws {
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let wrapper = try NostrIdentity.generate()
|
||||
// A valid NIP-44 v2 payload from the official test vectors. Its wire
|
||||
@@ -259,40 +470,36 @@ struct NostrProtocolTests {
|
||||
let event = NostrEvent(
|
||||
pubkey: wrapper.publicKeyHex,
|
||||
createdAt: Date(),
|
||||
kind: .giftWrap,
|
||||
kind: .legacyNIP59GiftWrap,
|
||||
tags: [["p", recipient.publicKeyHex]],
|
||||
content: standardPayload
|
||||
)
|
||||
let signed = try event.sign(with: wrapper.schnorrSigningKey())
|
||||
|
||||
expectInvalidCiphertext {
|
||||
_ = try NostrProtocol.decryptPrivateMessage(
|
||||
giftWrap: signed,
|
||||
_ = try NostrProtocol.decryptPrivateEnvelope(
|
||||
envelope: signed,
|
||||
recipientIdentity: recipient
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func decryptRejectsWrongOuterKind() throws {
|
||||
|
||||
@Test func decryptionFailsWithWrongRecipient() throws {
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
var giftWrap = try NostrProtocol.createPrivateMessage(
|
||||
content: "wrong outer kind",
|
||||
let wrongRecipient = try NostrIdentity.generate()
|
||||
|
||||
// Create message for recipient
|
||||
let envelope = try NostrProtocol.createPrivateEnvelope(
|
||||
content: "Secret message",
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
)
|
||||
giftWrap = NostrEvent(
|
||||
pubkey: giftWrap.pubkey,
|
||||
createdAt: Date(timeIntervalSince1970: TimeInterval(giftWrap.created_at)),
|
||||
kind: .textNote,
|
||||
tags: giftWrap.tags,
|
||||
content: giftWrap.content
|
||||
)
|
||||
|
||||
|
||||
expectInvalidEvent {
|
||||
_ = try NostrProtocol.decryptPrivateMessage(
|
||||
giftWrap: giftWrap,
|
||||
recipientIdentity: recipient
|
||||
_ = try NostrProtocol.decryptPrivateEnvelope(
|
||||
envelope: envelope,
|
||||
recipientIdentity: wrongRecipient
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -300,41 +507,41 @@ struct NostrProtocolTests {
|
||||
@Test func decryptRejectsInvalidSealSignature() throws {
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let giftWrap = try NostrProtocol.createPrivateMessageWithInvalidSealSignatureForTesting(
|
||||
let envelope = try NostrProtocol.createPrivateEnvelopeWithInvalidSealSignatureForTesting(
|
||||
content: "forged signature",
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
)
|
||||
|
||||
expectInvalidEvent {
|
||||
_ = try NostrProtocol.decryptPrivateMessage(
|
||||
giftWrap: giftWrap,
|
||||
_ = try NostrProtocol.decryptPrivateEnvelope(
|
||||
envelope: envelope,
|
||||
recipientIdentity: recipient
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func decryptRejectsSealRumorPubkeyMismatch() throws {
|
||||
@Test func decryptRejectsSealMessagePubkeyMismatch() throws {
|
||||
let claimedSender = try NostrIdentity.generate()
|
||||
let sealSigner = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let giftWrap = try NostrProtocol.createPrivateMessageWithMismatchedSealRumorPubkeyForTesting(
|
||||
let envelope = try NostrProtocol.createPrivateEnvelopeWithMismatchedSealMessagePubkeyForTesting(
|
||||
content: "spoofed sender",
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
rumorIdentity: claimedSender,
|
||||
messageIdentity: claimedSender,
|
||||
sealSignerIdentity: sealSigner
|
||||
)
|
||||
|
||||
expectInvalidEvent {
|
||||
_ = try NostrProtocol.decryptPrivateMessage(
|
||||
giftWrap: giftWrap,
|
||||
_ = try NostrProtocol.decryptPrivateEnvelope(
|
||||
envelope: envelope,
|
||||
recipientIdentity: recipient
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
func testAckRoundTripNIP44V2_Delivered() throws {
|
||||
func deliveredAckRoundTripsInsidePrivateEnvelope() throws {
|
||||
// Identities
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
@@ -348,19 +555,17 @@ struct NostrProtocolTests {
|
||||
"Failed to embed delivered ack"
|
||||
)
|
||||
|
||||
// Create NIP-17 gift wrap to recipient (uses NIP-44 v2 internally)
|
||||
let giftWrap = try NostrProtocol.createPrivateMessage(
|
||||
let envelope = try NostrProtocol.createPrivateEnvelope(
|
||||
content: embedded,
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
)
|
||||
|
||||
// Ensure v2 format was used for ciphertext
|
||||
#expect(giftWrap.content.hasPrefix("v2:"))
|
||||
#expect(envelope.content.hasPrefix(NostrProtocol.privateEnvelopeContentPrefix))
|
||||
|
||||
// Decrypt as recipient
|
||||
let (content, senderPubkey, _) = try NostrProtocol.decryptPrivateMessage(
|
||||
giftWrap: giftWrap,
|
||||
let (content, senderPubkey, _) = try NostrProtocol.decryptPrivateEnvelope(
|
||||
envelope: envelope,
|
||||
recipientIdentity: recipient
|
||||
)
|
||||
|
||||
@@ -385,7 +590,7 @@ struct NostrProtocolTests {
|
||||
}
|
||||
}
|
||||
|
||||
@Test func ackRoundTripNIP44V2_ReadReceipt() throws {
|
||||
@Test func readReceiptRoundTripsInsidePrivateEnvelope() throws {
|
||||
// Identities
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
@@ -397,16 +602,16 @@ struct NostrProtocolTests {
|
||||
"Failed to embed read ack"
|
||||
)
|
||||
|
||||
let giftWrap = try NostrProtocol.createPrivateMessage(
|
||||
let envelope = try NostrProtocol.createPrivateEnvelope(
|
||||
content: embedded,
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
)
|
||||
|
||||
#expect(giftWrap.content.hasPrefix("v2:"))
|
||||
#expect(envelope.content.hasPrefix(NostrProtocol.privateEnvelopeContentPrefix))
|
||||
|
||||
let (content, senderPubkey, _) = try NostrProtocol.decryptPrivateMessage(
|
||||
giftWrap: giftWrap,
|
||||
let (content, senderPubkey, _) = try NostrProtocol.decryptPrivateEnvelope(
|
||||
envelope: envelope,
|
||||
recipientIdentity: recipient
|
||||
)
|
||||
#expect(senderPubkey == sender.publicKeyHex)
|
||||
@@ -467,7 +672,6 @@ struct NostrProtocolTests {
|
||||
#expect(object["limit"] as? Int == 42)
|
||||
}
|
||||
|
||||
|
||||
@Test func inboundNostrEventRejectsTooManyTags() throws {
|
||||
var eventDict = Self.validInboundEventDict()
|
||||
eventDict["tags"] = Array(
|
||||
@@ -513,6 +717,33 @@ struct NostrProtocolTests {
|
||||
#expect(event.tags.count == 2)
|
||||
}
|
||||
|
||||
@Test func privateEnvelopeFiltersGiveEachMigrationKindAnIndependentRecoveryBudget() throws {
|
||||
let since = Date(timeIntervalSince1970: 1_234_567)
|
||||
let filters = NostrFilter.privateEnvelopeFiltersFor(
|
||||
pubkey: "recipient",
|
||||
since: since
|
||||
)
|
||||
|
||||
#expect(filters.count == 2)
|
||||
let objects = try filters.map { filter in
|
||||
let data = try JSONEncoder().encode(filter)
|
||||
return try #require(
|
||||
try JSONSerialization.jsonObject(with: data) as? [String: Any]
|
||||
)
|
||||
}
|
||||
#expect(objects.compactMap { $0["kinds"] as? [Int] } == [
|
||||
[NostrProtocol.EventKind.privateEnvelope.rawValue],
|
||||
[NostrProtocol.EventKind.legacyNIP59GiftWrap.rawValue]
|
||||
])
|
||||
for object in objects {
|
||||
#expect(object["#p"] as? [String] == ["recipient"])
|
||||
#expect(object["since"] as? Int == 1_234_567)
|
||||
#expect(object["limit"] as? Int ==
|
||||
TransportConfig.nostrPrivateEnvelopeFetchLimitPerKind
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
private static func validInboundEventDict() -> [String: Any] {
|
||||
[
|
||||
@@ -557,9 +788,6 @@ struct NostrProtocolTests {
|
||||
}
|
||||
|
||||
private func fixtureURL(name: String, extension fileExtension: String = "json") throws -> URL {
|
||||
// Bundle.module only exists under SwiftPM; the Xcode test targets
|
||||
// resolve resources through the test bundle (same pattern as
|
||||
// NoiseProtocolTests' NoiseTestVectors.json loader).
|
||||
#if SWIFT_PACKAGE
|
||||
let bundle = Bundle.module
|
||||
#else
|
||||
|
||||
@@ -188,7 +188,7 @@ struct PTTBurstPlayerTests {
|
||||
_ condition: () -> Bool,
|
||||
sourceLocation: SourceLocation = #_sourceLocation
|
||||
) async {
|
||||
let deadline = ContinuousClock.now.advanced(by: .seconds(TestConstants.settleTimeout))
|
||||
let deadline = ContinuousClock.now.advanced(by: .seconds(5))
|
||||
while !condition(), ContinuousClock.now < deadline {
|
||||
await Task.yield()
|
||||
try? await Task.sleep(nanoseconds: 1_000_000)
|
||||
|
||||
@@ -749,30 +749,12 @@ 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)
|
||||
}
|
||||
|
||||
@@ -203,134 +203,6 @@ 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")
|
||||
@@ -425,10 +297,8 @@ 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.sealRequests.count == sealCountBeforeRetry + 1)
|
||||
#expect(fixture.service.pendingDrops.count == BridgeCourierService.Limits.maxPendingDrops)
|
||||
#expect(fixture.service.pendingDrops.last?.dedupKey == firstID)
|
||||
}
|
||||
|
||||
@Test func oversizeDropConsumesSlotInsteadOfChurning() {
|
||||
|
||||
@@ -15,7 +15,7 @@ final class FavoritesPersistenceServiceTests: XCTestCase {
|
||||
|
||||
service.addFavorite(peerNoisePublicKey: peerKey, peerNostrPublicKey: "npub1alice", peerNickname: "Alice")
|
||||
|
||||
wait(for: [expectation], timeout: TestConstants.settleTimeout)
|
||||
wait(for: [expectation], timeout: 1.0)
|
||||
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 = TestConstants.settleTimeout,
|
||||
timeout: TimeInterval = 1.0,
|
||||
condition: @escaping @MainActor () -> Bool
|
||||
) async -> Bool {
|
||||
let deadline = Date().addingTimeInterval(timeout)
|
||||
|
||||
@@ -355,7 +355,7 @@ final class LocationStateManagerTests: XCTestCase {
|
||||
}
|
||||
|
||||
private func waitUntil(
|
||||
timeout: TimeInterval = TestConstants.settleTimeout,
|
||||
timeout: TimeInterval = 1.0,
|
||||
condition: @escaping @MainActor () -> Bool
|
||||
) async -> Bool {
|
||||
let deadline = Date().addingTimeInterval(timeout)
|
||||
|
||||
@@ -1,117 +0,0 @@
|
||||
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,42 +207,6 @@ 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,231 +79,18 @@ struct MessageRouterTests {
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
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 {
|
||||
func sendPrivate_connectedSendIsNotRetained() 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)
|
||||
|
||||
// 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")
|
||||
router.flushOutbox(for: peerID)
|
||||
#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
|
||||
@@ -605,31 +392,10 @@ 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 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 {
|
||||
func sendPrivate_connectedWithSecureSessionIsTrustedOutright() async {
|
||||
let peerID = PeerID(str: "00000000000000ab")
|
||||
let peerKey = Data(repeating: 0xAB, count: 32)
|
||||
let courier = PeerID(str: "00000000000000cc")
|
||||
@@ -649,11 +415,7 @@ struct MessageRouterTests {
|
||||
#expect(transport.sentPrivateMessages.map(\.messageID) == ["cs2"])
|
||||
#expect(transport.sentCourierMessages.isEmpty)
|
||||
router.flushOutbox(for: peerID)
|
||||
#expect(transport.sentPrivateMessages.count == 2)
|
||||
#expect(transport.sentCourierMessages.isEmpty)
|
||||
router.markDelivered("cs2")
|
||||
router.flushOutbox(for: peerID)
|
||||
#expect(transport.sentPrivateMessages.count == 2)
|
||||
#expect(transport.sentPrivateMessages.count == 1)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
@@ -765,52 +527,6 @@ 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
|
||||
@@ -866,82 +582,6 @@ 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
|
||||
@@ -1140,14 +780,12 @@ struct MessageRouterTests {
|
||||
protectedDataUnavailable = false
|
||||
restoredStore.retryDeferredLoad() // captures unseen durable + known wake
|
||||
|
||||
// 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.
|
||||
// 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.
|
||||
transport.connectedPeers.insert(peerID)
|
||||
transport.securePeers = [peerID]
|
||||
router.flushOutbox(for: peerID)
|
||||
router.markDelivered("recovery-gap-known")
|
||||
await Task.yield()
|
||||
await Task.yield()
|
||||
|
||||
@@ -1218,8 +856,7 @@ struct MessageRouterTests {
|
||||
restoredStore.retryDeferredLoad() // persists D+W and queues recovery
|
||||
transport.connectedPeers.insert(peerID)
|
||||
transport.securePeers = [peerID]
|
||||
router.flushOutbox(for: peerID)
|
||||
router.markDelivered("recovery-write-failure-known") // removes W before queued callback
|
||||
router.flushOutbox(for: peerID) // 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: TestConstants.negativeWaitWindow)
|
||||
wait(for: [notified], timeout: 1.0)
|
||||
context.notificationCenter.removeObserver(token)
|
||||
|
||||
XCTAssertFalse(context.service.userTorEnabled)
|
||||
@@ -138,67 +138,9 @@ 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>,
|
||||
selectedChannel: ChannelID = .mesh,
|
||||
selectedChannelSubject: CurrentValueSubject<ChannelID, Never>? = nil
|
||||
favorites: Set<Data>
|
||||
) -> NetworkActivationTestContext {
|
||||
let suiteName = "NetworkActivationServiceTests-\(UUID().uuidString)"
|
||||
let storage = UserDefaults(suiteName: suiteName)!
|
||||
@@ -206,8 +148,6 @@ 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()
|
||||
@@ -219,11 +159,6 @@ 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,
|
||||
@@ -243,7 +178,7 @@ final class NetworkActivationServiceTests: XCTestCase {
|
||||
}
|
||||
|
||||
private func waitUntil(
|
||||
timeout: TimeInterval = TestConstants.settleTimeout,
|
||||
timeout: TimeInterval = 1.0,
|
||||
condition: @escaping @MainActor () -> Bool
|
||||
) async -> Bool {
|
||||
let deadline = Date().addingTimeInterval(timeout)
|
||||
|
||||
@@ -69,45 +69,25 @@ final class NetworkReachabilityGateTests: XCTestCase {
|
||||
XCTAssertNil(d.pendingRemaining(at: t0.addingTimeInterval(2.5)))
|
||||
}
|
||||
|
||||
/// 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 }
|
||||
)
|
||||
func test_monitor_duplicateUpdatesDoNotPostponeOfflineCommit() async {
|
||||
let monitor = NWPathReachabilityMonitor(debounceInterval: 1.0)
|
||||
var received: [Bool] = []
|
||||
let cancellable = monitor.reachabilityPublisher.sink { received.append($0) }
|
||||
defer { cancellable.cancel() }
|
||||
|
||||
let start = Date()
|
||||
monitor.ingest(reachable: false)
|
||||
// Duplicate unsatisfied update mid-window (e.g. an interface detail
|
||||
// change while still offline).
|
||||
clock.now = clock.now.addingTimeInterval(0.1)
|
||||
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.
|
||||
monitor.ingest(reachable: false)
|
||||
// Past the original deadline, so the scheduled flush commits.
|
||||
clock.now = clock.now.addingTimeInterval(0.2)
|
||||
|
||||
// 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 }
|
||||
let committed = await waitUntil(timeout: 2.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
|
||||
@@ -199,7 +179,7 @@ final class NetworkReachabilityGateTests: XCTestCase {
|
||||
}
|
||||
|
||||
private func waitUntil(
|
||||
timeout: TimeInterval = TestConstants.settleTimeout,
|
||||
timeout: TimeInterval = 1.0,
|
||||
condition: @escaping @MainActor () -> Bool
|
||||
) async -> Bool {
|
||||
let deadline = Date().addingTimeInterval(timeout)
|
||||
@@ -259,13 +239,3 @@ 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: TestConstants.settleTimeout)
|
||||
let authenticated = await TestHelpers.waitUntil({ recorder.count >= 2 }, timeout: 5.0)
|
||||
#expect(authenticated)
|
||||
let generationAuthenticated = await TestHelpers.waitUntil(
|
||||
{ recorder.generationCount >= 1 },
|
||||
timeout: TestConstants.settleTimeout
|
||||
timeout: 5.0
|
||||
)
|
||||
#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.negativeWaitWindow
|
||||
timeout: TestConstants.shortTimeout
|
||||
)
|
||||
#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.negativeWaitWindow
|
||||
timeout: TestConstants.shortTimeout
|
||||
)
|
||||
#expect(!emittedReplacementAuthentication)
|
||||
}
|
||||
@@ -652,12 +652,12 @@ struct NoiseEncryptionServiceTests {
|
||||
)
|
||||
let retried = await TestHelpers.waitUntil(
|
||||
{ recorder.messages.count == 1 },
|
||||
timeout: TestConstants.longTimeout
|
||||
timeout: 1
|
||||
)
|
||||
#expect(retried)
|
||||
let retryExpired = await TestHelpers.waitUntil(
|
||||
{ !service.hasSession(with: peerID) },
|
||||
timeout: TestConstants.longTimeout
|
||||
timeout: 1
|
||||
)
|
||||
#expect(retryExpired)
|
||||
#expect(recorder.timeoutCount == 1)
|
||||
@@ -710,12 +710,7 @@ struct NoiseEncryptionServiceTests {
|
||||
let alice = NoiseEncryptionService(keychain: MockKeychain())
|
||||
let bob = NoiseEncryptionService(
|
||||
keychain: MockKeychain(),
|
||||
// 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,
|
||||
ordinaryResponderHandshakeTimeout: 0.06,
|
||||
ordinaryReconnectRollbackCooldown: 0.3
|
||||
)
|
||||
let mallory = NoiseEncryptionService(keychain: MockKeychain())
|
||||
@@ -746,12 +741,12 @@ struct NoiseEncryptionServiceTests {
|
||||
|
||||
let restored = await TestHelpers.waitUntil(
|
||||
{ bob.hasEstablishedSession(with: alicePeerID) },
|
||||
timeout: TestConstants.longTimeout
|
||||
timeout: 1
|
||||
)
|
||||
#expect(restored)
|
||||
let callbackArrived = await TestHelpers.waitUntil(
|
||||
{ recovery.timeoutCount == 1 },
|
||||
timeout: TestConstants.longTimeout
|
||||
timeout: 1
|
||||
)
|
||||
#expect(callbackArrived)
|
||||
|
||||
@@ -785,13 +780,7 @@ struct NoiseEncryptionServiceTests {
|
||||
let bob = NoiseEncryptionService(
|
||||
keychain: MockKeychain(),
|
||||
ordinaryHandshakeTimeout: 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
|
||||
ordinaryResponderHandshakeTimeout: 0.04
|
||||
)
|
||||
let alicePeerID = PeerID(publicKey: alice.getStaticPublicKeyData())
|
||||
let bobPeerID = PeerID(publicKey: bob.getStaticPublicKeyData())
|
||||
@@ -825,12 +814,12 @@ struct NoiseEncryptionServiceTests {
|
||||
// initiates one bounded convergence retry; drop that message 1 too.
|
||||
let retryPrepared = await TestHelpers.waitUntil(
|
||||
{ recovery.messages.count == 1 },
|
||||
timeout: TestConstants.longTimeout
|
||||
timeout: 1
|
||||
)
|
||||
#expect(retryPrepared)
|
||||
let retryExpired = await TestHelpers.waitUntil(
|
||||
{ !bob.hasSession(with: alicePeerID) },
|
||||
timeout: TestConstants.longTimeout
|
||||
timeout: 1
|
||||
)
|
||||
#expect(retryExpired)
|
||||
#expect(recovery.timeoutCount == 1)
|
||||
@@ -1037,7 +1026,7 @@ struct NoiseEncryptionServiceTests {
|
||||
|
||||
let requested = await TestHelpers.waitUntil(
|
||||
{ recovery.messages.count == 1 },
|
||||
timeout: TestConstants.longTimeout
|
||||
timeout: 1
|
||||
)
|
||||
#expect(requested)
|
||||
let retryMessage1 = try #require(recovery.messages.first)
|
||||
@@ -1246,17 +1235,9 @@ 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: 1.0
|
||||
ordinaryResponderHandshakeTimeout: 0.02
|
||||
)
|
||||
let mallory = NoiseEncryptionService(keychain: MockKeychain())
|
||||
let alicePeerID = PeerID(publicKey: alice.getStaticPublicKeyData())
|
||||
@@ -1272,17 +1253,9 @@ struct NoiseEncryptionServiceTests {
|
||||
)
|
||||
#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"
|
||||
)
|
||||
try? await Task.sleep(nanoseconds: 100_000_000)
|
||||
|
||||
#expect(bob.hasEstablishedSession(with: alicePeerID))
|
||||
let oldTransport = try alice.encrypt(
|
||||
Data("timeout rollback".utf8),
|
||||
for: bobPeerID
|
||||
|
||||
@@ -44,46 +44,6 @@ 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)
|
||||
|
||||
@@ -307,6 +267,588 @@ final class NostrRelayManagerTests: XCTestCase {
|
||||
XCTAssertEqual(context.manager.debugPendingMessageQueueCount, TransportConfig.nostrPendingSendQueueCap)
|
||||
}
|
||||
|
||||
func test_privateEnvelopeBatchEvictsEphemeralTrafficAndRemainsAtomic() async throws {
|
||||
let relayURL = "wss://private-batch-priority.example"
|
||||
let context = makeContext(
|
||||
permission: .denied,
|
||||
userTorEnabled: true,
|
||||
torEnforced: true,
|
||||
torIsReady: false
|
||||
)
|
||||
var ephemeralIDs: [String] = []
|
||||
for i in 0..<(TransportConfig.nostrPendingSendQueueCap - 1) {
|
||||
let event = try makeSignedEvent(
|
||||
content: "ephemeral-\(i)",
|
||||
kind: .ephemeralEvent
|
||||
)
|
||||
ephemeralIDs.append(event.id)
|
||||
context.manager.sendEvent(event, to: [relayURL])
|
||||
}
|
||||
let regular = try makeSignedEvent(content: "regular survives")
|
||||
context.manager.sendEvent(regular, to: [relayURL])
|
||||
XCTAssertEqual(
|
||||
context.manager.debugPendingMessageQueueCount,
|
||||
TransportConfig.nostrPendingSendQueueCap
|
||||
)
|
||||
|
||||
let primary = try makeSignedEvent(content: "primary", kind: .privateEnvelope)
|
||||
let legacy = try makeSignedEvent(content: "legacy", kind: .legacyNIP59GiftWrap)
|
||||
XCTAssertTrue(context.manager.sendPrivateEnvelopeBatch([primary, legacy], to: [relayURL]))
|
||||
|
||||
let batches = context.manager.debugPendingMessageQueueEventIDsByBatch
|
||||
let allIDs = Set(batches.flatMap { $0 })
|
||||
XCTAssertEqual(
|
||||
context.manager.debugPendingMessageQueueCount,
|
||||
TransportConfig.nostrPendingSendQueueCap
|
||||
)
|
||||
XCTAssertTrue(batches.contains([primary.id, legacy.id]))
|
||||
XCTAssertTrue(allIDs.contains(regular.id))
|
||||
XCTAssertFalse(allIDs.contains(ephemeralIDs[0]))
|
||||
XCTAssertFalse(allIDs.contains(ephemeralIDs[1]))
|
||||
|
||||
// Later low-priority traffic may evict another ephemeral event, but
|
||||
// never one half (or both halves) of the protected private batch.
|
||||
let lateEphemeral = try makeSignedEvent(content: "late", kind: .geohashPresence)
|
||||
context.manager.sendEvent(lateEphemeral, to: [relayURL])
|
||||
XCTAssertTrue(
|
||||
context.manager.debugPendingMessageQueueEventIDsByBatch
|
||||
.contains([primary.id, legacy.id])
|
||||
)
|
||||
}
|
||||
|
||||
func test_privateEnvelopeBatchDoesNotWriteStaleSocketUntilTorRecovers() async throws {
|
||||
let relayURL = "wss://private-batch-tor-gate.example"
|
||||
let context = makeContext(
|
||||
permission: .denied,
|
||||
userTorEnabled: true,
|
||||
torEnforced: true,
|
||||
torIsReady: true
|
||||
)
|
||||
context.manager.ensureConnections(to: [relayURL])
|
||||
let connected = await waitUntil {
|
||||
context.manager.relays.first(where: { $0.url == relayURL })?.isConnected == true
|
||||
}
|
||||
XCTAssertTrue(connected)
|
||||
let connection = try XCTUnwrap(context.sessionFactory.latestConnection(for: relayURL))
|
||||
|
||||
context.torWaiter.isReady = false
|
||||
let primary = try makeSignedEvent(content: "primary", kind: .privateEnvelope)
|
||||
let legacy = try makeSignedEvent(content: "legacy", kind: .legacyNIP59GiftWrap)
|
||||
XCTAssertTrue(context.manager.sendPrivateEnvelopeBatch([primary, legacy], to: [relayURL]))
|
||||
|
||||
try? await Task.sleep(nanoseconds: 20_000_000)
|
||||
XCTAssertTrue(connection.sentStrings.isEmpty)
|
||||
XCTAssertEqual(context.manager.debugPendingMessageQueueCount, 2)
|
||||
XCTAssertEqual(context.torWaiter.awaitCallCount, 1)
|
||||
|
||||
context.torWaiter.resolve(true)
|
||||
let flushed = await waitUntil {
|
||||
connection.sentStrings.count == 2
|
||||
}
|
||||
XCTAssertTrue(flushed)
|
||||
XCTAssertEqual(context.manager.debugPendingMessageQueueCount, 2)
|
||||
try await emitAcceptedPair([primary, legacy], on: connection)
|
||||
let acknowledged = await waitUntil {
|
||||
context.manager.debugPendingMessageQueueCount == 0
|
||||
}
|
||||
XCTAssertTrue(acknowledged)
|
||||
}
|
||||
|
||||
func test_privateEnvelopeBatchPrunesTerminalRelayAfterHealthyDelivery() async throws {
|
||||
let healthyURL = "wss://private-batch-healthy.example"
|
||||
let deadURL = "wss://private-batch-dead.example"
|
||||
let context = makeContext(permission: .denied)
|
||||
context.sessionFactory.pingErrorByURL[deadURL] = NSError(
|
||||
domain: NSURLErrorDomain,
|
||||
code: NSURLErrorCannotFindHost
|
||||
)
|
||||
let primary = try makeSignedEvent(content: "primary", kind: .privateEnvelope)
|
||||
let legacy = try makeSignedEvent(content: "legacy", kind: .legacyNIP59GiftWrap)
|
||||
var terminalFailureCount = 0
|
||||
|
||||
XCTAssertTrue(context.manager.sendPrivateEnvelopeBatch(
|
||||
[primary, legacy],
|
||||
to: [healthyURL, deadURL],
|
||||
terminalFailure: { terminalFailureCount += 1 }
|
||||
))
|
||||
|
||||
let healthyConnection = try XCTUnwrap(
|
||||
context.sessionFactory.latestConnection(for: healthyURL)
|
||||
)
|
||||
let written = await waitUntil {
|
||||
healthyConnection.sentStrings.count == 2
|
||||
}
|
||||
XCTAssertTrue(written)
|
||||
XCTAssertEqual(context.manager.debugPendingMessageQueueCount, 2)
|
||||
try await emitAcceptedPair([primary, legacy], on: healthyConnection)
|
||||
let initiallyAcknowledged = await waitUntil {
|
||||
context.manager.debugPendingMessageQueueCount == 0
|
||||
}
|
||||
XCTAssertTrue(initiallyAcknowledged)
|
||||
XCTAssertEqual(terminalFailureCount, 0)
|
||||
|
||||
// The terminal target is excluded during cooldown. More than one full
|
||||
// protected-capacity worth of subsequent logical sends must continue
|
||||
// to drain through the healthy relay instead of wedging globally.
|
||||
for _ in 0...100 {
|
||||
let sentCountBefore = healthyConnection.sentStrings.count
|
||||
XCTAssertTrue(context.manager.sendPrivateEnvelopeBatch(
|
||||
[primary, legacy],
|
||||
to: [healthyURL, deadURL]
|
||||
))
|
||||
let written = await waitUntil {
|
||||
healthyConnection.sentStrings.count == sentCountBefore + 2
|
||||
}
|
||||
XCTAssertTrue(written)
|
||||
try await emitAcceptedPair([primary, legacy], on: healthyConnection)
|
||||
let acknowledged = await waitUntil {
|
||||
context.manager.debugPendingMessageQueueCount == 0
|
||||
}
|
||||
XCTAssertTrue(acknowledged)
|
||||
}
|
||||
}
|
||||
|
||||
func test_privateEnvelopeBatchAllTerminalTargetsReportsWholeBatchFailure() async throws {
|
||||
let deadURL = "wss://private-batch-all-dead.example"
|
||||
let context = makeContext(permission: .denied)
|
||||
context.sessionFactory.pingErrorByURL[deadURL] = NSError(
|
||||
domain: NSURLErrorDomain,
|
||||
code: NSURLErrorCannotFindHost
|
||||
)
|
||||
let primary = try makeSignedEvent(content: "primary", kind: .privateEnvelope)
|
||||
let legacy = try makeSignedEvent(content: "legacy", kind: .legacyNIP59GiftWrap)
|
||||
var terminalFailureCount = 0
|
||||
|
||||
XCTAssertTrue(context.manager.sendPrivateEnvelopeBatch(
|
||||
[primary, legacy],
|
||||
to: [deadURL],
|
||||
terminalFailure: { terminalFailureCount += 1 }
|
||||
))
|
||||
|
||||
let failed = await waitUntil {
|
||||
terminalFailureCount == 1 &&
|
||||
context.manager.debugPendingMessageQueueCount == 0
|
||||
}
|
||||
XCTAssertTrue(failed)
|
||||
}
|
||||
|
||||
func test_privateEnvelopeBatchRejectsBeforeWritingWhenProtectedCapacityIsFull() async throws {
|
||||
let stalledRelayURL = "wss://private-batch-full.example"
|
||||
let connectedRelayURL = "wss://private-batch-connected.example"
|
||||
let context = makeContext(
|
||||
permission: .denied,
|
||||
userTorEnabled: true,
|
||||
torEnforced: true,
|
||||
torIsReady: true,
|
||||
torIsForeground: true
|
||||
)
|
||||
context.manager.ensureConnections(to: [connectedRelayURL])
|
||||
let connected = await waitUntil {
|
||||
context.manager.relays.first(where: { $0.url == connectedRelayURL })?.isConnected == true
|
||||
}
|
||||
XCTAssertTrue(connected)
|
||||
context.torForeground.value = false
|
||||
|
||||
let primary = try makeSignedEvent(content: "primary", kind: .privateEnvelope)
|
||||
let legacy = try makeSignedEvent(content: "legacy", kind: .legacyNIP59GiftWrap)
|
||||
let pair = [primary, legacy]
|
||||
|
||||
for _ in 0..<(TransportConfig.nostrPendingSendQueueCap / pair.count) {
|
||||
XCTAssertTrue(context.manager.sendPrivateEnvelopeBatch(pair, to: [stalledRelayURL]))
|
||||
}
|
||||
XCTAssertEqual(
|
||||
context.manager.debugPendingMessageQueueCount,
|
||||
TransportConfig.nostrPendingSendQueueCap
|
||||
)
|
||||
|
||||
let rejectedPrimary = try makeSignedEvent(content: "rejected-primary", kind: .privateEnvelope)
|
||||
let rejectedLegacy = try makeSignedEvent(content: "rejected-legacy", kind: .legacyNIP59GiftWrap)
|
||||
XCTAssertFalse(
|
||||
context.manager.sendPrivateEnvelopeBatch(
|
||||
[rejectedPrimary, rejectedLegacy],
|
||||
to: [connectedRelayURL]
|
||||
)
|
||||
)
|
||||
try? await Task.sleep(nanoseconds: 20_000_000)
|
||||
XCTAssertTrue(
|
||||
context.sessionFactory.latestConnection(for: connectedRelayURL)?.sentStrings.isEmpty == true
|
||||
)
|
||||
let queuedIDs = Set(
|
||||
context.manager.debugPendingMessageQueueEventIDsByBatch.flatMap { $0 }
|
||||
)
|
||||
XCTAssertFalse(queuedIDs.contains(rejectedPrimary.id))
|
||||
XCTAssertFalse(queuedIDs.contains(rejectedLegacy.id))
|
||||
}
|
||||
|
||||
func test_privateEnvelopeBatchStaysQueuedAndRetriesAfterFirstWriteFails() async throws {
|
||||
try await assertPrivateEnvelopeBatchWriteFailure(
|
||||
failureSequence: [NSError(domain: "send", code: 1)],
|
||||
expectedFirstConnectionWrites: 1
|
||||
)
|
||||
}
|
||||
|
||||
func test_privateEnvelopeBatchStaysQueuedAndRetriesAfterSecondWriteFails() async throws {
|
||||
try await assertPrivateEnvelopeBatchWriteFailure(
|
||||
failureSequence: [nil, NSError(domain: "send", code: 2)],
|
||||
expectedFirstConnectionWrites: 2
|
||||
)
|
||||
}
|
||||
|
||||
func test_privateEnvelopeBatchRemainsPendingUntilBothRelayOKsArrive() async throws {
|
||||
let relayURL = "wss://private-batch-two-write-commit.example"
|
||||
let context = makeContext(permission: .denied)
|
||||
let primary = try makeSignedEvent(content: "primary", kind: .privateEnvelope)
|
||||
let legacy = try makeSignedEvent(content: "legacy", kind: .legacyNIP59GiftWrap)
|
||||
|
||||
XCTAssertTrue(context.manager.sendPrivateEnvelopeBatch([primary, legacy], to: [relayURL]))
|
||||
let connection = try XCTUnwrap(context.sessionFactory.latestConnection(for: relayURL))
|
||||
connection.deferSendCompletions = true
|
||||
|
||||
let firstWriteStarted = await waitUntil { connection.sentStrings.count == 1 }
|
||||
XCTAssertTrue(firstWriteStarted)
|
||||
XCTAssertEqual(context.manager.debugPendingMessageQueueCount, 2)
|
||||
|
||||
connection.flushDeferredSendCompletions()
|
||||
let secondWriteStarted = await waitUntil { connection.sentStrings.count == 2 }
|
||||
XCTAssertTrue(secondWriteStarted)
|
||||
XCTAssertEqual(context.manager.debugPendingMessageQueueCount, 2)
|
||||
|
||||
connection.flushDeferredSendCompletions()
|
||||
try? await Task.sleep(nanoseconds: 20_000_000)
|
||||
XCTAssertEqual(context.manager.debugPendingMessageQueueCount, 2)
|
||||
|
||||
try connection.emitOK(eventID: primary.id, success: true, reason: "accepted")
|
||||
try? await Task.sleep(nanoseconds: 20_000_000)
|
||||
XCTAssertEqual(context.manager.debugPendingMessageQueueCount, 2)
|
||||
|
||||
try connection.emitOK(eventID: legacy.id, success: true, reason: "accepted")
|
||||
let committed = await waitUntil {
|
||||
context.manager.debugPendingMessageQueueCount == 0
|
||||
}
|
||||
XCTAssertTrue(committed)
|
||||
}
|
||||
|
||||
func test_privateEnvelopeBatchRejectedHalfReportsWholeBatchFailure() async throws {
|
||||
let relayURL = "wss://private-batch-rejected-half.example"
|
||||
let context = makeContext(permission: .denied)
|
||||
let primary = try makeSignedEvent(content: "primary", kind: .privateEnvelope)
|
||||
let legacy = try makeSignedEvent(content: "legacy", kind: .legacyNIP59GiftWrap)
|
||||
var terminalFailureCount = 0
|
||||
|
||||
XCTAssertTrue(context.manager.sendPrivateEnvelopeBatch(
|
||||
[primary, legacy],
|
||||
to: [relayURL],
|
||||
terminalFailure: { terminalFailureCount += 1 }
|
||||
))
|
||||
let connection = try XCTUnwrap(
|
||||
context.sessionFactory.latestConnection(for: relayURL)
|
||||
)
|
||||
let written = await waitUntil { connection.sentStrings.count == 2 }
|
||||
XCTAssertTrue(written)
|
||||
XCTAssertEqual(context.manager.debugPendingMessageQueueCount, 2)
|
||||
|
||||
try connection.emitOK(eventID: primary.id, success: true, reason: "accepted")
|
||||
try? await Task.sleep(nanoseconds: 20_000_000)
|
||||
XCTAssertEqual(context.manager.debugPendingMessageQueueCount, 2)
|
||||
XCTAssertEqual(terminalFailureCount, 0)
|
||||
|
||||
try connection.emitOK(eventID: legacy.id, success: false, reason: "blocked: policy")
|
||||
let failed = await waitUntil {
|
||||
context.manager.debugPendingMessageQueueCount == 0 &&
|
||||
terminalFailureCount == 1
|
||||
}
|
||||
XCTAssertTrue(failed)
|
||||
}
|
||||
|
||||
func test_privateEnvelopeBatchDuplicateOKsCountAsDurableAcceptance() async throws {
|
||||
let relayURL = "wss://private-batch-duplicate.example"
|
||||
let context = makeContext(permission: .denied)
|
||||
let primary = try makeSignedEvent(content: "primary", kind: .privateEnvelope)
|
||||
let legacy = try makeSignedEvent(content: "legacy", kind: .legacyNIP59GiftWrap)
|
||||
var terminalFailureCount = 0
|
||||
|
||||
XCTAssertTrue(context.manager.sendPrivateEnvelopeBatch(
|
||||
[primary, legacy],
|
||||
to: [relayURL],
|
||||
terminalFailure: { terminalFailureCount += 1 }
|
||||
))
|
||||
let connection = try XCTUnwrap(
|
||||
context.sessionFactory.latestConnection(for: relayURL)
|
||||
)
|
||||
let written = await waitUntil { connection.sentStrings.count == 2 }
|
||||
XCTAssertTrue(written)
|
||||
|
||||
for event in [primary, legacy] {
|
||||
try connection.emitOK(
|
||||
eventID: event.id,
|
||||
success: false,
|
||||
reason: " DuPlIcAtE: already have this event"
|
||||
)
|
||||
try? await Task.sleep(nanoseconds: 20_000_000)
|
||||
}
|
||||
let acknowledged = await waitUntil {
|
||||
context.manager.debugPendingMessageQueueCount == 0
|
||||
}
|
||||
XCTAssertTrue(acknowledged)
|
||||
XCTAssertEqual(terminalFailureCount, 0)
|
||||
}
|
||||
|
||||
func test_privateEnvelopeBatchAcknowledgementTimeoutReportsWholeBatchFailure() async throws {
|
||||
let relayURL = "wss://private-batch-ok-timeout.example"
|
||||
let context = makeContext(permission: .denied)
|
||||
let primary = try makeSignedEvent(content: "primary", kind: .privateEnvelope)
|
||||
let legacy = try makeSignedEvent(content: "legacy", kind: .legacyNIP59GiftWrap)
|
||||
var terminalFailureCount = 0
|
||||
|
||||
XCTAssertTrue(context.manager.sendPrivateEnvelopeBatch(
|
||||
[primary, legacy],
|
||||
to: [relayURL],
|
||||
terminalFailure: { terminalFailureCount += 1 }
|
||||
))
|
||||
let connection = try XCTUnwrap(
|
||||
context.sessionFactory.latestConnection(for: relayURL)
|
||||
)
|
||||
let timeoutScheduled = await waitUntil {
|
||||
connection.sentStrings.count == 2 &&
|
||||
context.scheduler.scheduled.contains {
|
||||
$0.delay == TransportConfig.nostrConfirmedSendAckTimeoutSeconds
|
||||
}
|
||||
}
|
||||
XCTAssertTrue(timeoutScheduled)
|
||||
XCTAssertEqual(context.manager.debugPendingMessageQueueCount, 2)
|
||||
NostrRelayManager.registerPendingPrivateEnvelope(id: primary.id)
|
||||
NostrRelayManager.registerPendingPrivateEnvelope(id: legacy.id)
|
||||
|
||||
context.scheduler.runNext()
|
||||
let failed = await waitUntil {
|
||||
context.manager.debugPendingMessageQueueCount == 0 &&
|
||||
terminalFailureCount == 1
|
||||
}
|
||||
XCTAssertTrue(failed)
|
||||
|
||||
try connection.emitOK(eventID: primary.id, success: true, reason: "late")
|
||||
try? await Task.sleep(nanoseconds: 20_000_000)
|
||||
XCTAssertEqual(terminalFailureCount, 1)
|
||||
XCTAssertEqual(context.manager.debugPendingMessageQueueCount, 0)
|
||||
XCTAssertFalse(NostrRelayManager.pendingPrivateEnvelopeIDs.contains(primary.id))
|
||||
XCTAssertFalse(NostrRelayManager.pendingPrivateEnvelopeIDs.contains(legacy.id))
|
||||
}
|
||||
|
||||
func test_privateEnvelopeBatchFastPrimaryRejectionStillWritesCompatibilityHalf() async throws {
|
||||
let relayURL = "wss://private-batch-early-reject.example"
|
||||
let context = makeContext(permission: .denied)
|
||||
let primary = try makeSignedEvent(content: "primary", kind: .privateEnvelope)
|
||||
let legacy = try makeSignedEvent(content: "legacy", kind: .legacyNIP59GiftWrap)
|
||||
var terminalFailureCount = 0
|
||||
|
||||
XCTAssertTrue(context.manager.sendPrivateEnvelopeBatch(
|
||||
[primary, legacy],
|
||||
to: [relayURL],
|
||||
terminalFailure: { terminalFailureCount += 1 }
|
||||
))
|
||||
let connection = try XCTUnwrap(
|
||||
context.sessionFactory.latestConnection(for: relayURL)
|
||||
)
|
||||
connection.deferSendCompletions = true
|
||||
let firstWriteStarted = await waitUntil { connection.sentStrings.count == 1 }
|
||||
XCTAssertTrue(firstWriteStarted)
|
||||
NostrRelayManager.registerPendingPrivateEnvelope(id: primary.id)
|
||||
NostrRelayManager.registerPendingPrivateEnvelope(id: legacy.id)
|
||||
|
||||
try connection.emitOK(eventID: primary.id, success: false, reason: "invalid: rejected")
|
||||
try? await Task.sleep(nanoseconds: 20_000_000)
|
||||
XCTAssertEqual(context.manager.debugPendingMessageQueueCount, 2)
|
||||
XCTAssertEqual(terminalFailureCount, 0)
|
||||
XCTAssertEqual(connection.sentStrings.count, 1)
|
||||
|
||||
// Completing the primary write must attempt the legacy 1059 even
|
||||
// though the relay has already rejected the provisional 1402.
|
||||
connection.flushDeferredSendCompletions()
|
||||
let compatibilityWriteStarted = await waitUntil {
|
||||
connection.sentStrings.count == 2
|
||||
}
|
||||
XCTAssertTrue(compatibilityWriteStarted)
|
||||
let compatibilityRequest = try XCTUnwrap(connection.sentStrings.last)
|
||||
let compatibilityJSON = try XCTUnwrap(
|
||||
JSONSerialization.jsonObject(
|
||||
with: Data(compatibilityRequest.utf8)
|
||||
) as? [Any]
|
||||
)
|
||||
let compatibilityEvent = try XCTUnwrap(
|
||||
compatibilityJSON.dropFirst().first as? [String: Any]
|
||||
)
|
||||
XCTAssertEqual(
|
||||
compatibilityEvent["kind"] as? Int,
|
||||
NostrProtocol.EventKind.legacyNIP59GiftWrap.rawValue
|
||||
)
|
||||
XCTAssertEqual(compatibilityEvent["id"] as? String, legacy.id)
|
||||
XCTAssertEqual(context.manager.debugPendingMessageQueueCount, 2)
|
||||
XCTAssertEqual(terminalFailureCount, 0)
|
||||
|
||||
connection.flushDeferredSendCompletions()
|
||||
let failed = await waitUntil {
|
||||
context.manager.debugPendingMessageQueueCount == 0 &&
|
||||
terminalFailureCount == 1
|
||||
}
|
||||
XCTAssertTrue(failed)
|
||||
XCTAssertEqual(connection.cancelCallCount, 0)
|
||||
XCTAssertEqual(
|
||||
context.manager.relays.first(where: { $0.url == relayURL })?.isConnected,
|
||||
true
|
||||
)
|
||||
XCTAssertEqual(terminalFailureCount, 1)
|
||||
XCTAssertFalse(NostrRelayManager.pendingPrivateEnvelopeIDs.contains(primary.id))
|
||||
XCTAssertFalse(NostrRelayManager.pendingPrivateEnvelopeIDs.contains(legacy.id))
|
||||
}
|
||||
|
||||
func test_privateEnvelopeBatchFastRejectionThenDisconnectReplaysWholePair() async throws {
|
||||
let relayURL = "wss://private-batch-early-reject-replay.example"
|
||||
let context = makeContext(permission: .denied)
|
||||
let primary = try makeSignedEvent(content: "primary", kind: .privateEnvelope)
|
||||
let legacy = try makeSignedEvent(content: "legacy", kind: .legacyNIP59GiftWrap)
|
||||
var terminalFailureCount = 0
|
||||
|
||||
XCTAssertTrue(context.manager.sendPrivateEnvelopeBatch(
|
||||
[primary, legacy],
|
||||
to: [relayURL],
|
||||
terminalFailure: { terminalFailureCount += 1 }
|
||||
))
|
||||
let firstConnection = try XCTUnwrap(
|
||||
context.sessionFactory.latestConnection(for: relayURL)
|
||||
)
|
||||
firstConnection.deferSendCompletions = true
|
||||
let firstWriteStarted = await waitUntil {
|
||||
firstConnection.sentStrings.count == 1
|
||||
}
|
||||
XCTAssertTrue(firstWriteStarted)
|
||||
|
||||
try firstConnection.emitOK(
|
||||
eventID: primary.id,
|
||||
success: false,
|
||||
reason: "invalid: rejected"
|
||||
)
|
||||
try? await Task.sleep(nanoseconds: 20_000_000)
|
||||
XCTAssertEqual(context.manager.debugPendingMessageQueueCount, 2)
|
||||
XCTAssertEqual(terminalFailureCount, 0)
|
||||
|
||||
// Replacing the connection before the sibling write clears the
|
||||
// attempt-scoped rejection. The durable pair must replay in full.
|
||||
context.manager.disconnect()
|
||||
context.manager.connect()
|
||||
let replacementReady = await waitUntil {
|
||||
let connections = context.sessionFactory.connectionsByURL[relayURL] ?? []
|
||||
guard connections.count == 2, let replacement = connections.last else {
|
||||
return false
|
||||
}
|
||||
return replacement.sentStrings.count == 2
|
||||
}
|
||||
XCTAssertTrue(replacementReady)
|
||||
let replacement = try XCTUnwrap(
|
||||
context.sessionFactory.latestConnection(for: relayURL)
|
||||
)
|
||||
try await emitAcceptedPair([primary, legacy], on: replacement)
|
||||
let acknowledged = await waitUntil {
|
||||
context.manager.debugPendingMessageQueueCount == 0
|
||||
}
|
||||
XCTAssertTrue(acknowledged)
|
||||
XCTAssertEqual(terminalFailureCount, 0)
|
||||
|
||||
// The canceled connection's late completion cannot send its sibling
|
||||
// or mutate the replacement attempt.
|
||||
firstConnection.flushDeferredSendCompletions()
|
||||
try? await Task.sleep(nanoseconds: 20_000_000)
|
||||
XCTAssertEqual(firstConnection.sentStrings.count, 1)
|
||||
XCTAssertEqual(context.manager.debugPendingMessageQueueCount, 0)
|
||||
XCTAssertEqual(terminalFailureCount, 0)
|
||||
}
|
||||
|
||||
func test_privateEnvelopeBatchDisconnectDuringWriteReplaysOnReplacementConnection() async throws {
|
||||
let relayURL = "wss://private-batch-background-reconnect.example"
|
||||
let context = makeContext(permission: .denied)
|
||||
let primary = try makeSignedEvent(content: "primary", kind: .privateEnvelope)
|
||||
let legacy = try makeSignedEvent(content: "legacy", kind: .legacyNIP59GiftWrap)
|
||||
|
||||
XCTAssertTrue(context.manager.sendPrivateEnvelopeBatch([primary, legacy], to: [relayURL]))
|
||||
let firstConnection = try XCTUnwrap(
|
||||
context.sessionFactory.latestConnection(for: relayURL)
|
||||
)
|
||||
firstConnection.deferSendCompletions = true
|
||||
let firstWriteStarted = await waitUntil { firstConnection.sentStrings.count == 1 }
|
||||
XCTAssertTrue(firstWriteStarted)
|
||||
|
||||
// Backgrounding cancels the socket while its first write callback is
|
||||
// still outstanding. The pair must remain replayable in the queue.
|
||||
context.manager.disconnect()
|
||||
XCTAssertEqual(context.manager.debugPendingMessageQueueCount, 2)
|
||||
context.manager.connect()
|
||||
|
||||
let replacementReady = await waitUntil {
|
||||
let connections = context.sessionFactory.connectionsByURL[relayURL] ?? []
|
||||
guard connections.count == 2, let replacement = connections.last else {
|
||||
return false
|
||||
}
|
||||
return replacement.sentStrings.count == 2
|
||||
}
|
||||
XCTAssertTrue(replacementReady)
|
||||
let replacement = try XCTUnwrap(
|
||||
context.sessionFactory.latestConnection(for: relayURL)
|
||||
)
|
||||
XCTAssertEqual(context.manager.debugPendingMessageQueueCount, 2)
|
||||
try await emitAcceptedPair([primary, legacy], on: replacement)
|
||||
let acknowledged = await waitUntil {
|
||||
context.manager.debugPendingMessageQueueCount == 0
|
||||
}
|
||||
XCTAssertTrue(acknowledged)
|
||||
|
||||
// A late success callback from the canceled socket must neither send
|
||||
// the legacy half on that stale socket nor disturb the completed pair.
|
||||
firstConnection.flushDeferredSendCompletions()
|
||||
try? await Task.sleep(nanoseconds: 20_000_000)
|
||||
XCTAssertEqual(firstConnection.sentStrings.count, 1)
|
||||
XCTAssertEqual(context.manager.debugPendingMessageQueueCount, 0)
|
||||
}
|
||||
|
||||
private func assertPrivateEnvelopeBatchWriteFailure(
|
||||
failureSequence: [Error?],
|
||||
expectedFirstConnectionWrites: Int
|
||||
) async throws {
|
||||
let relayURL = "wss://private-batch-write-failure.example"
|
||||
let context = makeContext(permission: .denied)
|
||||
let primary = try makeSignedEvent(content: "primary", kind: .privateEnvelope)
|
||||
let legacy = try makeSignedEvent(content: "legacy", kind: .legacyNIP59GiftWrap)
|
||||
|
||||
XCTAssertTrue(context.manager.sendPrivateEnvelopeBatch([primary, legacy], to: [relayURL]))
|
||||
let firstConnection = try XCTUnwrap(context.sessionFactory.latestConnection(for: relayURL))
|
||||
firstConnection.sendErrorSequence = failureSequence
|
||||
|
||||
let stayedQueued = await waitUntil {
|
||||
firstConnection.sentStrings.count == expectedFirstConnectionWrites &&
|
||||
context.manager.debugPendingMessageQueueEventIDsByBatch.contains([primary.id, legacy.id])
|
||||
}
|
||||
XCTAssertTrue(stayedQueued)
|
||||
XCTAssertEqual(context.manager.debugPendingMessageQueueCount, 2)
|
||||
|
||||
// The failed socket is disconnected with bounded backoff. Its queue
|
||||
// item is reused—not re-admitted—and the replacement retries both
|
||||
// copies before the pair is finally removed.
|
||||
XCTAssertFalse(context.scheduler.scheduled.isEmpty)
|
||||
context.scheduler.runNext()
|
||||
let replacementReady = await waitUntil {
|
||||
guard let replacement = context.sessionFactory.latestConnection(for: relayURL),
|
||||
replacement !== firstConnection else { return false }
|
||||
return replacement.sentStrings.count == 2
|
||||
}
|
||||
XCTAssertTrue(replacementReady)
|
||||
let replacement = try XCTUnwrap(
|
||||
context.sessionFactory.latestConnection(for: relayURL)
|
||||
)
|
||||
try await emitAcceptedPair([primary, legacy], on: replacement)
|
||||
let acknowledged = await waitUntil {
|
||||
context.manager.debugPendingMessageQueueCount == 0
|
||||
}
|
||||
XCTAssertTrue(acknowledged)
|
||||
}
|
||||
|
||||
func test_sendEvent_waitsForTorReadinessBeforeSending() async throws {
|
||||
let relayURL = "wss://tor-ready.example"
|
||||
let context = makeContext(permission: .denied, userTorEnabled: true, torEnforced: true, torIsReady: false)
|
||||
@@ -588,6 +1130,52 @@ final class NostrRelayManagerTests: XCTestCase {
|
||||
XCTAssertEqual(context.sessionFactory.latestConnection(for: relayURL)?.sentStrings.count, 1)
|
||||
}
|
||||
|
||||
func test_subscribe_multiplePrivateEnvelopeFiltersEncodesIndependentLimits() async throws {
|
||||
let relayURL = "wss://private-recovery-filters.example"
|
||||
let context = makeContext(permission: .denied)
|
||||
let filters = NostrFilter.privateEnvelopeFiltersFor(
|
||||
pubkey: "recipient",
|
||||
since: Date(timeIntervalSince1970: 1_234_567)
|
||||
)
|
||||
|
||||
context.manager.subscribe(
|
||||
filters: filters,
|
||||
id: "private-recovery",
|
||||
relayUrls: [relayURL],
|
||||
handler: { _ in }
|
||||
)
|
||||
|
||||
let sent = await waitUntil {
|
||||
context.sessionFactory.latestConnection(for: relayURL)?.sentStrings.count == 1
|
||||
}
|
||||
XCTAssertTrue(sent)
|
||||
let request = try XCTUnwrap(
|
||||
context.sessionFactory.latestConnection(for: relayURL)?.sentStrings.first
|
||||
)
|
||||
let data = try XCTUnwrap(request.data(using: .utf8))
|
||||
let array = try XCTUnwrap(
|
||||
try JSONSerialization.jsonObject(with: data) as? [Any]
|
||||
)
|
||||
XCTAssertEqual(array.count, 4)
|
||||
XCTAssertEqual(array[0] as? String, "REQ")
|
||||
XCTAssertEqual(array[1] as? String, "private-recovery")
|
||||
let encodedFilters = try [array[2], array[3]].map {
|
||||
try XCTUnwrap($0 as? [String: Any])
|
||||
}
|
||||
XCTAssertEqual(encodedFilters.compactMap { $0["kinds"] as? [Int] }, [
|
||||
[NostrProtocol.EventKind.privateEnvelope.rawValue],
|
||||
[NostrProtocol.EventKind.legacyNIP59GiftWrap.rawValue]
|
||||
])
|
||||
for filter in encodedFilters {
|
||||
XCTAssertEqual(
|
||||
filter["limit"] as? Int,
|
||||
TransportConfig.nostrPrivateEnvelopeFetchLimitPerKind
|
||||
)
|
||||
XCTAssertEqual(filter["#p"] as? [String], ["recipient"])
|
||||
XCTAssertEqual(filter["since"] as? Int, 1_234_567)
|
||||
}
|
||||
}
|
||||
|
||||
func test_subscribe_coalescesDuplicateRequestsBeforeTorReadyAndDefersEOSE() async throws {
|
||||
let relayURL = "wss://tor-subscribe-coalesce.example"
|
||||
let context = makeContext(permission: .denied, userTorEnabled: true, torEnforced: true, torIsReady: false)
|
||||
@@ -894,7 +1482,7 @@ final class NostrRelayManagerTests: XCTestCase {
|
||||
|
||||
/// The relay boundary is the single signature-verification point for the
|
||||
/// whole inbound path (downstream pipelines no longer re-verify), so a
|
||||
/// tampered gift wrap (kind 1059, the DM/mailbox path) must be dropped
|
||||
/// tampered private envelope (the DM/mailbox path) must be dropped
|
||||
/// here — and must not poison the dedup cache against the genuine copy.
|
||||
func test_receiveGiftWrap_tamperedSignatureIsDroppedAndDoesNotPoisonDedup() async throws {
|
||||
let firstRelayURL = "wss://giftwrap-one.example"
|
||||
@@ -902,7 +1490,7 @@ final class NostrRelayManagerTests: XCTestCase {
|
||||
let context = makeContext(permission: .denied)
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let giftWrap = try NostrProtocol.createPrivateMessage(
|
||||
let giftWrap = try NostrProtocol.createPrivateEnvelope(
|
||||
content: "psst",
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
@@ -960,7 +1548,7 @@ final class NostrRelayManagerTests: XCTestCase {
|
||||
try context.sessionFactory.latestConnection(for: relayURL)?.emitEventMessage(subscriptionID: "ordered", event: event)
|
||||
}
|
||||
|
||||
let allDelivered = await waitUntil(timeout: TestConstants.settleTimeout) {
|
||||
let allDelivered = await waitUntil(timeout: 5.0) {
|
||||
receivedIDs.count == events.count
|
||||
}
|
||||
XCTAssertTrue(allDelivered)
|
||||
@@ -1006,7 +1594,7 @@ final class NostrRelayManagerTests: XCTestCase {
|
||||
}
|
||||
try context.sessionFactory.latestConnection(for: quietRelayURL)?.emitEventMessage(subscriptionID: "quiet", event: quietEvent)
|
||||
|
||||
let quietDelivered = await waitUntil(timeout: TestConstants.settleTimeout) { quietDeliveredAfterBusyCount >= 0 }
|
||||
let quietDelivered = await waitUntil(timeout: 5.0) { 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
|
||||
@@ -1019,7 +1607,7 @@ final class NostrRelayManagerTests: XCTestCase {
|
||||
)
|
||||
|
||||
// Both relays still drain fully and in order.
|
||||
let allDelivered = await waitUntil(timeout: TestConstants.settleTimeout) {
|
||||
let allDelivered = await waitUntil(timeout: 5.0) {
|
||||
busyDeliveredCount == busyEvents.count
|
||||
}
|
||||
XCTAssertTrue(allDelivered)
|
||||
@@ -1079,11 +1667,11 @@ final class NostrRelayManagerTests: XCTestCase {
|
||||
XCTAssertTrue(secondDelivered)
|
||||
}
|
||||
|
||||
func test_okMessages_clearPendingGiftWrapIDs() async throws {
|
||||
func test_okMessages_clearPendingPrivateEnvelopeIDs() async throws {
|
||||
let relayURL = "wss://ok.example"
|
||||
let context = makeContext(permission: .denied)
|
||||
let successID = "gift-wrap-success"
|
||||
let failureID = "gift-wrap-failure"
|
||||
let successID = "private-envelope-success"
|
||||
let failureID = "private-envelope-failure"
|
||||
|
||||
context.manager.ensureConnections(to: [relayURL])
|
||||
let connected = await waitUntil {
|
||||
@@ -1092,17 +1680,17 @@ final class NostrRelayManagerTests: XCTestCase {
|
||||
}
|
||||
XCTAssertTrue(connected)
|
||||
|
||||
NostrRelayManager.registerPendingGiftWrap(id: successID)
|
||||
NostrRelayManager.registerPendingPrivateEnvelope(id: successID)
|
||||
try context.sessionFactory.latestConnection(for: relayURL)?.emitOK(eventID: successID, success: true, reason: "ok")
|
||||
let successCleared = await waitUntil {
|
||||
!NostrRelayManager.pendingGiftWrapIDs.contains(successID)
|
||||
!NostrRelayManager.pendingPrivateEnvelopeIDs.contains(successID)
|
||||
}
|
||||
XCTAssertTrue(successCleared)
|
||||
|
||||
NostrRelayManager.registerPendingGiftWrap(id: failureID)
|
||||
NostrRelayManager.registerPendingPrivateEnvelope(id: failureID)
|
||||
try context.sessionFactory.latestConnection(for: relayURL)?.emitOK(eventID: failureID, success: false, reason: "rejected")
|
||||
let failureCleared = await waitUntil {
|
||||
!NostrRelayManager.pendingGiftWrapIDs.contains(failureID)
|
||||
!NostrRelayManager.pendingPrivateEnvelopeIDs.contains(failureID)
|
||||
}
|
||||
XCTAssertTrue(failureCleared)
|
||||
}
|
||||
@@ -1775,58 +2363,6 @@ 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> = [],
|
||||
@@ -1835,8 +2371,6 @@ 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)
|
||||
@@ -1864,9 +2398,7 @@ final class NostrRelayManagerTests: XCTestCase {
|
||||
scheduler.schedule(delay: delay, action: action)
|
||||
},
|
||||
now: { clock.now },
|
||||
jitterUnit: jitterUnit,
|
||||
notificationCenter: notificationCenter,
|
||||
customRelays: { customRelays.urls }
|
||||
jitterUnit: jitterUnit
|
||||
)
|
||||
)
|
||||
return RelayManagerTestContext(
|
||||
@@ -1888,12 +2420,31 @@ final class NostrRelayManagerTests: XCTestCase {
|
||||
return filter
|
||||
}
|
||||
|
||||
private func makeSignedEvent(content: String) throws -> NostrEvent {
|
||||
private func emitAcceptedPair(
|
||||
_ events: [NostrEvent],
|
||||
on connection: MockRelayConnection
|
||||
) async throws {
|
||||
for event in events {
|
||||
try connection.emitOK(
|
||||
eventID: event.id,
|
||||
success: true,
|
||||
reason: "accepted"
|
||||
)
|
||||
// Each inbound frame consumes the mock receive handler. Let the
|
||||
// manager re-arm it before delivering the next relay response.
|
||||
try? await Task.sleep(nanoseconds: 20_000_000)
|
||||
}
|
||||
}
|
||||
|
||||
private func makeSignedEvent(
|
||||
content: String,
|
||||
kind: NostrProtocol.EventKind = .textNote
|
||||
) throws -> NostrEvent {
|
||||
let identity = try NostrIdentity.generate()
|
||||
let event = NostrEvent(
|
||||
pubkey: identity.publicKeyHex,
|
||||
createdAt: Date(),
|
||||
kind: .textNote,
|
||||
kind: kind,
|
||||
tags: [],
|
||||
content: content
|
||||
)
|
||||
@@ -1907,7 +2458,7 @@ final class NostrRelayManagerTests: XCTestCase {
|
||||
}
|
||||
|
||||
private func waitUntil(
|
||||
timeout: TimeInterval = TestConstants.settleTimeout,
|
||||
timeout: TimeInterval = 1.0,
|
||||
condition: @escaping @MainActor () -> Bool
|
||||
) async -> Bool {
|
||||
let deadline = Date().addingTimeInterval(timeout)
|
||||
@@ -1941,16 +2492,6 @@ 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 {
|
||||
@@ -2043,6 +2584,7 @@ private final class MockRelaySessionFactory: NostrRelaySessionProtocol {
|
||||
private final class MockRelayConnection: NostrRelayConnectionProtocol {
|
||||
private let pingError: Error?
|
||||
var sendError: Error?
|
||||
var sendErrorSequence: [Error?] = []
|
||||
private var receiveHandler: ((Result<URLSessionWebSocketTask.Message, Error>) -> Void)?
|
||||
private(set) var resumeCallCount = 0
|
||||
private(set) var cancelCallCount = 0
|
||||
@@ -2072,14 +2614,15 @@ private final class MockRelayConnection: NostrRelayConnectionProtocol {
|
||||
}
|
||||
|
||||
var deferSendCompletions = false
|
||||
private var deferredSendCompletions: [(Error?) -> Void] = []
|
||||
private var deferredSendCompletions: [(error: Error?, completion: (Error?) -> Void)] = []
|
||||
|
||||
func send(_ message: URLSessionWebSocketTask.Message, completionHandler: @escaping (Error?) -> Void) {
|
||||
sentMessages.append(message)
|
||||
let error = sendErrorSequence.isEmpty ? sendError : sendErrorSequence.removeFirst()
|
||||
if deferSendCompletions {
|
||||
deferredSendCompletions.append(completionHandler)
|
||||
deferredSendCompletions.append((error, completionHandler))
|
||||
} else {
|
||||
completionHandler(sendError)
|
||||
completionHandler(error)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2087,7 +2630,7 @@ private final class MockRelayConnection: NostrRelayConnectionProtocol {
|
||||
let pending = deferredSendCompletions
|
||||
deferredSendCompletions = []
|
||||
pending.forEach {
|
||||
$0(sendError)
|
||||
$0.completion($0.error)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -131,7 +131,7 @@ struct NostrTransportTests {
|
||||
#expect(undeliverable)
|
||||
}
|
||||
|
||||
@Test("Private message resolves short peer ID and emits decryptable packet")
|
||||
@Test("Private message resolves short peer ID and emits both migration formats")
|
||||
@MainActor
|
||||
func sendPrivateMessageResolvesShortPeerID() async throws {
|
||||
let keychain = MockKeychain()
|
||||
@@ -153,8 +153,8 @@ struct NostrTransportTests {
|
||||
favoriteStatusForNoiseKey: { _ in nil },
|
||||
favoriteStatusForPeerID: { $0 == shortPeerID ? relationship : nil },
|
||||
currentIdentity: { sender },
|
||||
registerPendingGiftWrap: probe.recordPendingGiftWrap(id:),
|
||||
sendEvent: probe.record(event:),
|
||||
registerPendingPrivateEnvelope: probe.recordPendingPrivateEnvelope(id:),
|
||||
sendPrivateEnvelopeBatch: { events, _ in probe.record(batch: events) },
|
||||
scheduleAfter: { delay, action in
|
||||
probe.enqueueScheduledAction(delay: delay, action: action)
|
||||
}
|
||||
@@ -164,8 +164,12 @@ struct NostrTransportTests {
|
||||
|
||||
transport.sendPrivateMessage("hello over nostr", to: shortPeerID, recipientNickname: "Carol", messageID: "pm-1")
|
||||
|
||||
let didSend = await TestHelpers.waitUntil({ probe.sentEvents.count == 1 }, timeout: TestConstants.settleTimeout)
|
||||
let didSend = await TestHelpers.waitUntil({ probe.sentEvents.count == 2 }, timeout: 5.0)
|
||||
#expect(didSend)
|
||||
#expect(probe.sentEvents.map(\.kind) == [
|
||||
NostrProtocol.EventKind.privateEnvelope.rawValue,
|
||||
NostrProtocol.EventKind.legacyNIP59GiftWrap.rawValue
|
||||
])
|
||||
let result = try decodeEmbeddedPayload(from: probe.sentEvents[0], recipient: recipient)
|
||||
let privateMessage = try decodePrivateMessage(from: result.payload)
|
||||
|
||||
@@ -173,7 +177,583 @@ struct NostrTransportTests {
|
||||
#expect(privateMessage.messageID == "pm-1")
|
||||
#expect(privateMessage.content == "hello over nostr")
|
||||
#expect(result.packet.recipientID == shortPeerID.routingData)
|
||||
#expect(probe.pendingGiftWrapIDs.isEmpty)
|
||||
#expect(probe.pendingPrivateEnvelopeIDs.isEmpty)
|
||||
}
|
||||
|
||||
@Test("Coordinated migration always publishes primary and compatibility envelopes")
|
||||
@MainActor
|
||||
func migrationAlwaysDualPublishes() async throws {
|
||||
let keychain = MockKeychain()
|
||||
let idBridge = NostrIdentityBridge(keychain: keychain)
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let noiseKey = Data((192..<224).map(UInt8.init))
|
||||
let peerID = PeerID(hexData: noiseKey)
|
||||
let relationship = makeRelationship(
|
||||
peerNoisePublicKey: noiseKey,
|
||||
peerNostrPublicKey: recipient.npub,
|
||||
peerNickname: "Migration peer"
|
||||
)
|
||||
|
||||
let migrationProbe = NostrTransportProbe()
|
||||
let migrationTransport = NostrTransport(
|
||||
keychain: keychain,
|
||||
idBridge: idBridge,
|
||||
dependencies: makeDependencies(
|
||||
favoriteStatusForNoiseKey: { $0 == noiseKey ? relationship : nil },
|
||||
currentIdentity: { sender },
|
||||
sendPrivateEnvelopeBatch: { events, _ in migrationProbe.record(batch: events) }
|
||||
)
|
||||
)
|
||||
migrationTransport.senderPeerID = PeerID(str: "0123456789abcdef")
|
||||
migrationTransport.sendPrivateMessage(
|
||||
"migration payload",
|
||||
to: peerID,
|
||||
recipientNickname: "Migration peer",
|
||||
messageID: "migration-pm"
|
||||
)
|
||||
|
||||
let sentPair = await TestHelpers.waitUntil(
|
||||
{ migrationProbe.sentEvents.count == 2 },
|
||||
timeout: 5.0
|
||||
)
|
||||
#expect(sentPair)
|
||||
#expect(migrationProbe.sentEvents.map(\.kind) == [
|
||||
NostrProtocol.EventKind.privateEnvelope.rawValue,
|
||||
NostrProtocol.EventKind.legacyNIP59GiftWrap.rawValue
|
||||
])
|
||||
for event in migrationProbe.sentEvents {
|
||||
let result = try decodeEmbeddedPayload(from: event, recipient: recipient)
|
||||
let message = try decodePrivateMessage(from: result.payload)
|
||||
#expect(message.messageID == "migration-pm")
|
||||
#expect(message.content == "migration payload")
|
||||
}
|
||||
}
|
||||
|
||||
@Test("Rejected migration batch does not register half-delivery state")
|
||||
@MainActor
|
||||
func rejectedMigrationBatchRegistersNothing() async throws {
|
||||
let keychain = MockKeychain()
|
||||
let idBridge = NostrIdentityBridge(keychain: keychain)
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let probe = NostrTransportProbe()
|
||||
var rejectedKinds: [Int] = []
|
||||
let transport = NostrTransport(
|
||||
keychain: keychain,
|
||||
idBridge: idBridge,
|
||||
dependencies: makeDependencies(
|
||||
currentIdentity: { sender },
|
||||
registerPendingPrivateEnvelope: probe.recordPendingPrivateEnvelope(id:),
|
||||
sendPrivateEnvelopeBatch: { events, _ in
|
||||
rejectedKinds = events.map(\.kind)
|
||||
return false
|
||||
}
|
||||
)
|
||||
)
|
||||
transport.senderPeerID = PeerID(str: "0123456789abcdef")
|
||||
|
||||
transport.sendPrivateMessageGeohash(
|
||||
content: "must stay atomic",
|
||||
toRecipientHex: recipient.publicKeyHex,
|
||||
from: sender,
|
||||
messageID: "atomic-reject"
|
||||
)
|
||||
|
||||
let attempted = await TestHelpers.waitUntil({ rejectedKinds.count == 2 }, timeout: 5.0)
|
||||
#expect(attempted)
|
||||
#expect(rejectedKinds == [
|
||||
NostrProtocol.EventKind.privateEnvelope.rawValue,
|
||||
NostrProtocol.EventKind.legacyNIP59GiftWrap.rawValue
|
||||
])
|
||||
#expect(probe.pendingPrivateEnvelopeIDs.isEmpty)
|
||||
}
|
||||
|
||||
@Test("Rejected user message emits a visible failed-delivery event")
|
||||
@MainActor
|
||||
func rejectedUserMessageEmitsFailureEvent() async throws {
|
||||
let keychain = MockKeychain()
|
||||
let idBridge = NostrIdentityBridge(keychain: keychain)
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let eventProbe = NostrTransportEventProbe()
|
||||
let transport = NostrTransport(
|
||||
keychain: keychain,
|
||||
idBridge: idBridge,
|
||||
dependencies: makeDependencies(
|
||||
currentIdentity: { sender },
|
||||
sendPrivateEnvelopeBatch: { _, _ in false }
|
||||
)
|
||||
)
|
||||
transport.senderPeerID = PeerID(str: "0123456789abcdef")
|
||||
transport.eventDelegate = eventProbe
|
||||
|
||||
transport.sendPrivateMessageGeohash(
|
||||
content: "must fail visibly",
|
||||
toRecipientHex: recipient.publicKeyHex,
|
||||
from: sender,
|
||||
messageID: "visible-reject"
|
||||
)
|
||||
|
||||
let reported = await TestHelpers.waitUntil(
|
||||
{ eventProbe.failedMessageIDs == ["visible-reject"] },
|
||||
timeout: 5.0
|
||||
)
|
||||
#expect(reported)
|
||||
}
|
||||
|
||||
@Test("Envelope construction failure rejects visibly without publishing")
|
||||
@MainActor
|
||||
func envelopeConstructionFailureRejectsVisibly() async throws {
|
||||
let keychain = MockKeychain()
|
||||
let idBridge = NostrIdentityBridge(keychain: keychain)
|
||||
let sender = try NostrIdentity.generate()
|
||||
let eventProbe = NostrTransportEventProbe()
|
||||
let publicationProbe = NostrTransportProbe()
|
||||
let transport = NostrTransport(
|
||||
keychain: keychain,
|
||||
idBridge: idBridge,
|
||||
dependencies: makeDependencies(
|
||||
currentIdentity: { sender },
|
||||
sendPrivateEnvelopeBatch: { events, _ in
|
||||
publicationProbe.record(batch: events)
|
||||
}
|
||||
)
|
||||
)
|
||||
transport.senderPeerID = PeerID(str: "0123456789abcdef")
|
||||
transport.eventDelegate = eventProbe
|
||||
|
||||
// Non-empty but invalid hex reaches envelope construction after the
|
||||
// embedded BitChat packet succeeds, reproducing the throwing batch
|
||||
// builder path without allocating an oversized test fixture.
|
||||
let accepted = transport.sendPrivateMessageGeohash(
|
||||
content: "must fail before sent",
|
||||
toRecipientHex: "not-a-hex-public-key",
|
||||
from: sender,
|
||||
messageID: "build-reject"
|
||||
)
|
||||
|
||||
#expect(!accepted)
|
||||
#expect(publicationProbe.sentEvents.isEmpty)
|
||||
#expect(eventProbe.failedMessageIDs == ["build-reject"])
|
||||
}
|
||||
|
||||
@Test("Unencodable user message rejects visibly without publishing")
|
||||
@MainActor
|
||||
func unencodableUserMessageRejectsVisibly() async throws {
|
||||
let keychain = MockKeychain()
|
||||
let idBridge = NostrIdentityBridge(keychain: keychain)
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let eventProbe = NostrTransportEventProbe()
|
||||
let publicationProbe = NostrTransportProbe()
|
||||
let transport = NostrTransport(
|
||||
keychain: keychain,
|
||||
idBridge: idBridge,
|
||||
dependencies: makeDependencies(
|
||||
currentIdentity: { sender },
|
||||
sendPrivateEnvelopeBatch: { events, _ in
|
||||
publicationProbe.record(batch: events)
|
||||
}
|
||||
)
|
||||
)
|
||||
transport.senderPeerID = PeerID(str: "0123456789abcdef")
|
||||
transport.eventDelegate = eventProbe
|
||||
|
||||
// PrivateMessagePacket uses the deployed UInt8 content length. Do not
|
||||
// create a larger wire shape that released clients cannot decode.
|
||||
let accepted = transport.sendPrivateMessageGeohash(
|
||||
content: String(repeating: "x", count: 256),
|
||||
toRecipientHex: recipient.publicKeyHex,
|
||||
from: sender,
|
||||
messageID: "packet-reject"
|
||||
)
|
||||
|
||||
#expect(!accepted)
|
||||
#expect(publicationProbe.sentEvents.isEmpty)
|
||||
#expect(eventProbe.failedMessageIDs == ["packet-reject"])
|
||||
}
|
||||
|
||||
@Test("Unencodable direct message emits a visible failure")
|
||||
@MainActor
|
||||
func unencodableDirectMessageEmitsVisibleFailure() async throws {
|
||||
let keychain = MockKeychain()
|
||||
let idBridge = NostrIdentityBridge(keychain: keychain)
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let noiseKey = Data((224..<256).map(UInt8.init))
|
||||
let peerID = PeerID(hexData: noiseKey)
|
||||
let relationship = makeRelationship(
|
||||
peerNoisePublicKey: noiseKey,
|
||||
peerNostrPublicKey: recipient.npub,
|
||||
peerNickname: "Oversized peer"
|
||||
)
|
||||
let eventProbe = NostrTransportEventProbe()
|
||||
let publicationProbe = NostrTransportProbe()
|
||||
let transport = NostrTransport(
|
||||
keychain: keychain,
|
||||
idBridge: idBridge,
|
||||
dependencies: makeDependencies(
|
||||
favoriteStatusForNoiseKey: {
|
||||
$0 == noiseKey ? relationship : nil
|
||||
},
|
||||
currentIdentity: { sender },
|
||||
sendPrivateEnvelopeBatch: { events, _ in
|
||||
publicationProbe.record(batch: events)
|
||||
}
|
||||
)
|
||||
)
|
||||
transport.senderPeerID = PeerID(str: "0123456789abcdef")
|
||||
transport.eventDelegate = eventProbe
|
||||
|
||||
transport.sendPrivateMessage(
|
||||
String(repeating: "x", count: 256),
|
||||
to: peerID,
|
||||
recipientNickname: "Oversized peer",
|
||||
messageID: "direct-packet-reject"
|
||||
)
|
||||
|
||||
let failed = await TestHelpers.waitUntil(
|
||||
{
|
||||
eventProbe.failedMessageIDs
|
||||
== ["direct-packet-reject"]
|
||||
},
|
||||
timeout: 5.0
|
||||
)
|
||||
#expect(failed)
|
||||
#expect(publicationProbe.sentEvents.isEmpty)
|
||||
}
|
||||
|
||||
@Test("Direct message with an invalid npub emits a visible failure")
|
||||
@MainActor
|
||||
func invalidDirectRecipientNpubEmitsVisibleFailure() async throws {
|
||||
let keychain = MockKeychain()
|
||||
let idBridge = NostrIdentityBridge(keychain: keychain)
|
||||
let sender = try NostrIdentity.generate()
|
||||
let noiseKey = Data(repeating: 0xA5, count: 32)
|
||||
let peerID = PeerID(hexData: noiseKey)
|
||||
let relationship = makeRelationship(
|
||||
peerNoisePublicKey: noiseKey,
|
||||
peerNostrPublicKey: "not-a-valid-npub",
|
||||
peerNickname: "Invalid npub peer"
|
||||
)
|
||||
let eventProbe = NostrTransportEventProbe()
|
||||
let publicationProbe = NostrTransportProbe()
|
||||
let transport = NostrTransport(
|
||||
keychain: keychain,
|
||||
idBridge: idBridge,
|
||||
dependencies: makeDependencies(
|
||||
favoriteStatusForNoiseKey: {
|
||||
$0 == noiseKey ? relationship : nil
|
||||
},
|
||||
currentIdentity: { sender },
|
||||
sendPrivateEnvelopeBatch: { events, _ in
|
||||
publicationProbe.record(batch: events)
|
||||
}
|
||||
)
|
||||
)
|
||||
transport.senderPeerID = PeerID(str: "0123456789abcdef")
|
||||
transport.eventDelegate = eventProbe
|
||||
|
||||
transport.sendPrivateMessage(
|
||||
"must fail before publication",
|
||||
to: peerID,
|
||||
recipientNickname: "Invalid npub peer",
|
||||
messageID: "invalid-npub"
|
||||
)
|
||||
|
||||
let failed = await TestHelpers.waitUntil(
|
||||
{ eventProbe.failedMessageIDs == ["invalid-npub"] },
|
||||
timeout: 5.0
|
||||
)
|
||||
#expect(failed)
|
||||
#expect(publicationProbe.sentEvents.isEmpty)
|
||||
}
|
||||
|
||||
@Test("Direct message without a resolvable recipient emits a visible failure")
|
||||
@MainActor
|
||||
func missingDirectRecipientEmitsVisibleFailure() async throws {
|
||||
let keychain = MockKeychain()
|
||||
let idBridge = NostrIdentityBridge(keychain: keychain)
|
||||
let sender = try NostrIdentity.generate()
|
||||
let peerID = PeerID(hexData: Data(repeating: 0xC3, count: 32))
|
||||
let eventProbe = NostrTransportEventProbe()
|
||||
let publicationProbe = NostrTransportProbe()
|
||||
let transport = NostrTransport(
|
||||
keychain: keychain,
|
||||
idBridge: idBridge,
|
||||
dependencies: makeDependencies(
|
||||
currentIdentity: { sender },
|
||||
sendPrivateEnvelopeBatch: { events, _ in
|
||||
publicationProbe.record(batch: events)
|
||||
}
|
||||
)
|
||||
)
|
||||
transport.senderPeerID = PeerID(str: "0123456789abcdef")
|
||||
transport.eventDelegate = eventProbe
|
||||
|
||||
transport.sendPrivateMessage(
|
||||
"must fail without recipient",
|
||||
to: peerID,
|
||||
recipientNickname: "Unknown peer",
|
||||
messageID: "missing-recipient"
|
||||
)
|
||||
|
||||
let failed = await TestHelpers.waitUntil(
|
||||
{ eventProbe.failedMessageIDs == ["missing-recipient"] },
|
||||
timeout: 5.0
|
||||
)
|
||||
#expect(failed)
|
||||
#expect(publicationProbe.sentEvents.isEmpty)
|
||||
}
|
||||
|
||||
@Test("Direct message without a current identity emits a visible failure")
|
||||
@MainActor
|
||||
func missingDirectSenderIdentityEmitsVisibleFailure() async throws {
|
||||
let keychain = MockKeychain()
|
||||
let idBridge = NostrIdentityBridge(keychain: keychain)
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let noiseKey = Data(repeating: 0x5A, count: 32)
|
||||
let peerID = PeerID(hexData: noiseKey)
|
||||
let relationship = makeRelationship(
|
||||
peerNoisePublicKey: noiseKey,
|
||||
peerNostrPublicKey: recipient.npub,
|
||||
peerNickname: "Missing identity peer"
|
||||
)
|
||||
let eventProbe = NostrTransportEventProbe()
|
||||
let publicationProbe = NostrTransportProbe()
|
||||
let transport = NostrTransport(
|
||||
keychain: keychain,
|
||||
idBridge: idBridge,
|
||||
dependencies: makeDependencies(
|
||||
favoriteStatusForNoiseKey: {
|
||||
$0 == noiseKey ? relationship : nil
|
||||
},
|
||||
currentIdentity: { nil },
|
||||
sendPrivateEnvelopeBatch: { events, _ in
|
||||
publicationProbe.record(batch: events)
|
||||
}
|
||||
)
|
||||
)
|
||||
transport.senderPeerID = PeerID(str: "0123456789abcdef")
|
||||
transport.eventDelegate = eventProbe
|
||||
|
||||
transport.sendPrivateMessage(
|
||||
"must fail without identity",
|
||||
to: peerID,
|
||||
recipientNickname: "Missing identity peer",
|
||||
messageID: "missing-identity"
|
||||
)
|
||||
|
||||
let failed = await TestHelpers.waitUntil(
|
||||
{ eventProbe.failedMessageIDs == ["missing-identity"] },
|
||||
timeout: 5.0
|
||||
)
|
||||
#expect(failed)
|
||||
#expect(publicationProbe.sentEvents.isEmpty)
|
||||
}
|
||||
|
||||
@Test("Rejected favorite notification retains and retries the exact pair")
|
||||
@MainActor
|
||||
func rejectedFavoriteNotificationRetriesExactPair() async throws {
|
||||
let keychain = MockKeychain()
|
||||
let idBridge = NostrIdentityBridge(keychain: keychain)
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let noiseKey = Data((96..<128).map(UInt8.init))
|
||||
let fullPeerID = PeerID(hexData: noiseKey)
|
||||
let relationship = makeRelationship(
|
||||
peerNoisePublicKey: noiseKey,
|
||||
peerNostrPublicKey: recipient.npub,
|
||||
peerNickname: "Retry favorite"
|
||||
)
|
||||
let probe = NostrTransportProbe()
|
||||
var attempts: [[String]] = []
|
||||
weak var releasedTransport: NostrTransport?
|
||||
do {
|
||||
let transport = NostrTransport(
|
||||
keychain: keychain,
|
||||
idBridge: idBridge,
|
||||
dependencies: makeDependencies(
|
||||
favoriteStatusForNoiseKey: { $0 == noiseKey ? relationship : nil },
|
||||
currentIdentity: { sender },
|
||||
sendPrivateEnvelopeBatch: { events, _ in
|
||||
attempts.append(events.map(\.id))
|
||||
return attempts.count > 1
|
||||
},
|
||||
scheduleAfter: { delay, action in
|
||||
probe.enqueueScheduledAction(delay: delay, action: action)
|
||||
}
|
||||
)
|
||||
)
|
||||
transport.senderPeerID = PeerID(str: "0123456789abcdef")
|
||||
releasedTransport = transport
|
||||
|
||||
transport.sendFavoriteNotification(to: fullPeerID, isFavorite: true)
|
||||
let retryScheduled = await TestHelpers.waitUntil(
|
||||
{ attempts.count == 1 && probe.scheduledActionCount == 1 },
|
||||
timeout: 5.0
|
||||
)
|
||||
#expect(retryScheduled)
|
||||
}
|
||||
#expect(releasedTransport == nil)
|
||||
#expect(probe.runNextScheduledAction())
|
||||
|
||||
let retried = await TestHelpers.waitUntil({ attempts.count == 2 }, timeout: 5.0)
|
||||
#expect(retried)
|
||||
#expect(attempts[0] == attempts[1])
|
||||
}
|
||||
|
||||
@Test("Rejected delivery acknowledgement remains queued for retry")
|
||||
@MainActor
|
||||
func rejectedDeliveryAckRetries() async throws {
|
||||
let keychain = MockKeychain()
|
||||
let idBridge = NostrIdentityBridge(keychain: keychain)
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let noiseKey = Data((128..<160).map(UInt8.init))
|
||||
let fullPeerID = PeerID(hexData: noiseKey)
|
||||
let relationship = makeRelationship(
|
||||
peerNoisePublicKey: noiseKey,
|
||||
peerNostrPublicKey: recipient.npub,
|
||||
peerNickname: "Retry ack"
|
||||
)
|
||||
let probe = NostrTransportProbe()
|
||||
var attempts: [[String]] = []
|
||||
let transport = NostrTransport(
|
||||
keychain: keychain,
|
||||
idBridge: idBridge,
|
||||
dependencies: makeDependencies(
|
||||
favoriteStatusForNoiseKey: { $0 == noiseKey ? relationship : nil },
|
||||
currentIdentity: { sender },
|
||||
sendPrivateEnvelopeBatch: { events, _ in
|
||||
attempts.append(events.map(\.id))
|
||||
return attempts.count > 1
|
||||
},
|
||||
scheduleAfter: { delay, action in
|
||||
probe.enqueueScheduledAction(delay: delay, action: action)
|
||||
}
|
||||
)
|
||||
)
|
||||
transport.senderPeerID = PeerID(str: "0123456789abcdef")
|
||||
|
||||
transport.sendDeliveryAck(for: "retry-ack", to: fullPeerID)
|
||||
let firstAttempt = await TestHelpers.waitUntil(
|
||||
{ attempts.count == 1 && probe.scheduledActionCount >= 1 },
|
||||
timeout: 5.0
|
||||
)
|
||||
#expect(firstAttempt)
|
||||
|
||||
for _ in 0..<3 where attempts.count < 2 {
|
||||
_ = probe.runNextScheduledAction()
|
||||
_ = await TestHelpers.waitUntil(
|
||||
{ attempts.count == 2 || probe.scheduledActionCount > 0 },
|
||||
timeout: 1.0
|
||||
)
|
||||
}
|
||||
#expect(attempts.count == 2)
|
||||
#expect(attempts[0] == attempts[1])
|
||||
}
|
||||
|
||||
@Test("Control retry queue is bounded and evicted callbacks are harmless")
|
||||
@MainActor
|
||||
func controlRetryQueueIsBounded() async throws {
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let events = try NostrProtocol.createPrivateEnvelopePublicationBatch(
|
||||
content: "bounded retry fixture",
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
)
|
||||
let probe = NostrTransportProbe()
|
||||
var retryAttempts = 0
|
||||
let queue = NostrPrivateEnvelopeRetryQueue(
|
||||
sendPrivateEnvelopeBatch: { _, _ in
|
||||
retryAttempts += 1
|
||||
return false
|
||||
},
|
||||
registerPendingPrivateEnvelope: { _ in },
|
||||
scheduleAfter: { delay, action in
|
||||
probe.enqueueScheduledAction(delay: delay, action: action)
|
||||
}
|
||||
)
|
||||
|
||||
for index in 0...TransportConfig.nostrPrivateEnvelopeRetryQueueCap {
|
||||
queue.enqueue(
|
||||
key: "control-\(index)",
|
||||
events: events,
|
||||
registerPending: false
|
||||
)
|
||||
}
|
||||
|
||||
#expect(queue.debugPendingCount == TransportConfig.nostrPrivateEnvelopeRetryQueueCap)
|
||||
#expect(!queue.debugContains(key: "control-0"))
|
||||
#expect(queue.debugContains(key: "control-1"))
|
||||
|
||||
// The oldest callback was scheduled before eviction. Running it must
|
||||
// observe the missing key and return without touching dependencies.
|
||||
#expect(probe.runNextScheduledAction())
|
||||
try? await Task.sleep(nanoseconds: 20_000_000)
|
||||
#expect(retryAttempts == 0)
|
||||
|
||||
queue.removeAll()
|
||||
#expect(queue.debugPendingCount == 0)
|
||||
#expect(probe.runNextScheduledAction())
|
||||
try? await Task.sleep(nanoseconds: 20_000_000)
|
||||
#expect(retryAttempts == 0)
|
||||
}
|
||||
|
||||
@Test("Multiple transports share one globally bounded control retry owner")
|
||||
@MainActor
|
||||
func multipleTransportsShareControlRetryQueue() async throws {
|
||||
let keychain = MockKeychain()
|
||||
let idBridge = NostrIdentityBridge(keychain: keychain)
|
||||
let sender = try NostrIdentity.generate()
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let events = try NostrProtocol.createPrivateEnvelopePublicationBatch(
|
||||
content: "shared retry fixture",
|
||||
recipientPubkey: recipient.publicKeyHex,
|
||||
senderIdentity: sender
|
||||
)
|
||||
let probe = NostrTransportProbe()
|
||||
var retryAttempts = 0
|
||||
let sharedQueue = NostrPrivateEnvelopeRetryQueue(
|
||||
sendPrivateEnvelopeBatch: { _, _ in
|
||||
retryAttempts += 1
|
||||
return false
|
||||
},
|
||||
registerPendingPrivateEnvelope: { _ in },
|
||||
scheduleAfter: { delay, action in
|
||||
probe.enqueueScheduledAction(delay: delay, action: action)
|
||||
}
|
||||
)
|
||||
let first = NostrTransport(
|
||||
keychain: keychain,
|
||||
idBridge: idBridge,
|
||||
dependencies: makeDependencies(envelopeRetryQueue: sharedQueue)
|
||||
)
|
||||
let second = NostrTransport(
|
||||
keychain: keychain,
|
||||
idBridge: idBridge,
|
||||
dependencies: makeDependencies(envelopeRetryQueue: sharedQueue)
|
||||
)
|
||||
|
||||
first.debugEnqueueControlRetry(key: "shared", events: events)
|
||||
second.debugEnqueueControlRetry(key: "shared", events: events)
|
||||
#expect(first.debugControlRetryCount == 1)
|
||||
#expect(second.debugControlRetryCount == 1)
|
||||
|
||||
for index in 0...TransportConfig.nostrPrivateEnvelopeRetryQueueCap {
|
||||
let transport = index.isMultiple(of: 2) ? first : second
|
||||
transport.debugEnqueueControlRetry(key: "global-\(index)", events: events)
|
||||
}
|
||||
#expect(first.debugControlRetryCount == TransportConfig.nostrPrivateEnvelopeRetryQueueCap)
|
||||
#expect(second.debugControlRetryCount == TransportConfig.nostrPrivateEnvelopeRetryQueueCap)
|
||||
|
||||
// The first scheduled callback belongs to the now-evicted shared key.
|
||||
#expect(probe.runNextScheduledAction())
|
||||
try? await Task.sleep(nanoseconds: 20_000_000)
|
||||
#expect(retryAttempts == 0)
|
||||
}
|
||||
|
||||
@Test("Favorite notification embeds current npub")
|
||||
@@ -198,8 +778,8 @@ struct NostrTransportTests {
|
||||
favoriteStatusForNoiseKey: { $0 == noiseKey ? relationship : nil },
|
||||
favoriteStatusForPeerID: { _ in nil },
|
||||
currentIdentity: { sender },
|
||||
registerPendingGiftWrap: probe.recordPendingGiftWrap(id:),
|
||||
sendEvent: probe.record(event:),
|
||||
registerPendingPrivateEnvelope: probe.recordPendingPrivateEnvelope(id:),
|
||||
sendPrivateEnvelopeBatch: { events, _ in probe.record(batch: events) },
|
||||
scheduleAfter: { delay, action in
|
||||
probe.enqueueScheduledAction(delay: delay, action: action)
|
||||
}
|
||||
@@ -209,7 +789,7 @@ struct NostrTransportTests {
|
||||
|
||||
transport.sendFavoriteNotification(to: fullPeerID, isFavorite: true)
|
||||
|
||||
let didSend = await TestHelpers.waitUntil({ probe.sentEvents.count == 1 }, timeout: TestConstants.settleTimeout)
|
||||
let didSend = await TestHelpers.waitUntil({ probe.sentEvents.count == 2 }, timeout: 5.0)
|
||||
#expect(didSend)
|
||||
let result = try decodeEmbeddedPayload(from: probe.sentEvents[0], recipient: recipient)
|
||||
let privateMessage = try decodePrivateMessage(from: result.payload)
|
||||
@@ -239,8 +819,8 @@ struct NostrTransportTests {
|
||||
favoriteStatusForNoiseKey: { $0 == noiseKey ? relationship : nil },
|
||||
favoriteStatusForPeerID: { _ in nil },
|
||||
currentIdentity: { sender },
|
||||
registerPendingGiftWrap: probe.recordPendingGiftWrap(id:),
|
||||
sendEvent: probe.record(event:),
|
||||
registerPendingPrivateEnvelope: probe.recordPendingPrivateEnvelope(id:),
|
||||
sendPrivateEnvelopeBatch: { events, _ in probe.record(batch: events) },
|
||||
scheduleAfter: { delay, action in
|
||||
probe.enqueueScheduledAction(delay: delay, action: action)
|
||||
}
|
||||
@@ -250,7 +830,7 @@ struct NostrTransportTests {
|
||||
|
||||
transport.sendDeliveryAck(for: "ack-1", to: fullPeerID)
|
||||
|
||||
let didSend = await TestHelpers.waitUntil({ probe.sentEvents.count == 1 }, timeout: TestConstants.settleTimeout)
|
||||
let didSend = await TestHelpers.waitUntil({ probe.sentEvents.count == 2 }, timeout: 5.0)
|
||||
#expect(didSend)
|
||||
let result = try decodeEmbeddedPayload(from: probe.sentEvents[0], recipient: recipient)
|
||||
|
||||
@@ -259,9 +839,9 @@ struct NostrTransportTests {
|
||||
#expect(result.packet.recipientID == fullPeerID.toShort().routingData)
|
||||
}
|
||||
|
||||
@Test("Geohash private message registers pending gift wrap")
|
||||
@Test("Geohash private message registers pending private envelope")
|
||||
@MainActor
|
||||
func sendPrivateMessageGeohashRegistersPendingGiftWrap() async throws {
|
||||
func sendPrivateMessageGeohashRegistersPendingPrivateEnvelope() async throws {
|
||||
let keychain = MockKeychain()
|
||||
let idBridge = NostrIdentityBridge(keychain: keychain)
|
||||
let sender = try NostrIdentity.generate()
|
||||
@@ -272,8 +852,8 @@ struct NostrTransportTests {
|
||||
idBridge: idBridge,
|
||||
dependencies: makeDependencies(
|
||||
currentIdentity: { sender },
|
||||
registerPendingGiftWrap: probe.recordPendingGiftWrap(id:),
|
||||
sendEvent: probe.record(event:),
|
||||
registerPendingPrivateEnvelope: probe.recordPendingPrivateEnvelope(id:),
|
||||
sendPrivateEnvelopeBatch: { events, _ in probe.record(batch: events) },
|
||||
scheduleAfter: { delay, action in
|
||||
probe.enqueueScheduledAction(delay: delay, action: action)
|
||||
}
|
||||
@@ -288,7 +868,7 @@ struct NostrTransportTests {
|
||||
messageID: "geo-1"
|
||||
)
|
||||
|
||||
let didSend = await TestHelpers.waitUntil({ probe.sentEvents.count == 1 }, timeout: TestConstants.settleTimeout)
|
||||
let didSend = await TestHelpers.waitUntil({ probe.sentEvents.count == 2 }, timeout: 5.0)
|
||||
#expect(didSend)
|
||||
let event = probe.sentEvents[0]
|
||||
let result = try decodeEmbeddedPayload(from: event, recipient: recipient)
|
||||
@@ -297,7 +877,7 @@ struct NostrTransportTests {
|
||||
#expect(privateMessage.messageID == "geo-1")
|
||||
#expect(privateMessage.content == "geo hello")
|
||||
#expect(result.packet.recipientID == nil)
|
||||
#expect(probe.pendingGiftWrapIDs == [event.id])
|
||||
#expect(probe.pendingPrivateEnvelopeIDs == probe.sentEvents.map(\.id))
|
||||
}
|
||||
|
||||
@Test("Read receipt queue sends in order and waits for scheduler")
|
||||
@@ -322,8 +902,8 @@ struct NostrTransportTests {
|
||||
favoriteStatusForNoiseKey: { $0 == noiseKey ? relationship : nil },
|
||||
favoriteStatusForPeerID: { _ in nil },
|
||||
currentIdentity: { sender },
|
||||
registerPendingGiftWrap: probe.recordPendingGiftWrap(id:),
|
||||
sendEvent: probe.record(event:),
|
||||
registerPendingPrivateEnvelope: probe.recordPendingPrivateEnvelope(id:),
|
||||
sendPrivateEnvelopeBatch: { events, _ in probe.record(batch: events) },
|
||||
scheduleAfter: { delay, action in
|
||||
probe.enqueueScheduledAction(delay: delay, action: action)
|
||||
}
|
||||
@@ -338,20 +918,20 @@ struct NostrTransportTests {
|
||||
transport.sendReadReceipt(second, to: fullPeerID)
|
||||
|
||||
let readReceiptTimeout: TimeInterval = 5.0
|
||||
let sentFirst = await TestHelpers.waitUntil({ probe.sentEvents.count >= 1 }, timeout: readReceiptTimeout)
|
||||
try #require(sentFirst, "Expected first queued read receipt event")
|
||||
let sentFirst = await TestHelpers.waitUntil({ probe.sentEvents.count == 2 }, timeout: readReceiptTimeout)
|
||||
try #require(sentFirst, "Expected first queued read receipt pair")
|
||||
let scheduledThrottle = await TestHelpers.waitUntil({ probe.scheduledActionCount == 1 }, timeout: readReceiptTimeout)
|
||||
try #require(scheduledThrottle, "Expected queued throttle action after first read receipt")
|
||||
let firstEvent = try #require(probe.sentEvents.first, "Expected first queued read receipt event")
|
||||
let firstEvent = try #require(probe.sentEvents.first, "Expected first queued read receipt pair")
|
||||
let firstPayload = try decodeEmbeddedPayload(from: firstEvent, recipient: recipient).payload
|
||||
#expect(firstPayload.type == .readReceipt)
|
||||
#expect(String(data: firstPayload.data, encoding: .utf8) == "read-1")
|
||||
|
||||
try #require(probe.runNextScheduledAction(), "Expected queued throttle action after first read receipt")
|
||||
|
||||
let sentSecond = await TestHelpers.waitUntil({ probe.sentEvents.count >= 2 }, timeout: readReceiptTimeout)
|
||||
try #require(sentSecond, "Expected second read receipt after running throttle action")
|
||||
let secondEvent = try #require(probe.sentEvents.last, "Expected second queued read receipt event")
|
||||
let sentSecond = await TestHelpers.waitUntil({ probe.sentEvents.count == 4 }, timeout: readReceiptTimeout)
|
||||
try #require(sentSecond, "Expected second read receipt pair after running throttle action")
|
||||
let secondEvent = probe.sentEvents[2]
|
||||
let secondPayload = try decodeEmbeddedPayload(from: secondEvent, recipient: recipient).payload
|
||||
#expect(secondPayload.type == .readReceipt)
|
||||
#expect(String(data: secondPayload.data, encoding: .utf8) == "read-2")
|
||||
@@ -419,10 +999,14 @@ struct NostrTransportTests {
|
||||
favoriteStatusForNoiseKey: @escaping @MainActor (Data) -> FavoriteRelationship? = { _ in nil },
|
||||
favoriteStatusForPeerID: @escaping @MainActor (PeerID) -> FavoriteRelationship? = { _ in nil },
|
||||
currentIdentity: @escaping @MainActor () throws -> NostrIdentity? = { nil },
|
||||
registerPendingGiftWrap: @escaping @MainActor (String) -> Void = { _ in },
|
||||
sendEvent: @escaping @MainActor (NostrEvent) -> Void = { _ in },
|
||||
registerPendingPrivateEnvelope: @escaping @MainActor (String) -> Void = { _ in },
|
||||
sendPrivateEnvelopeBatch: @escaping @MainActor (
|
||||
[NostrEvent],
|
||||
@escaping @MainActor () -> Void
|
||||
) -> Bool = { _, _ in true },
|
||||
scheduleAfter: @escaping @Sendable (TimeInterval, @escaping @Sendable () -> Void) -> Void = { _, _ in },
|
||||
relayConnectivity: @escaping @MainActor () -> AnyPublisher<Bool, Never> = { Just(false).eraseToAnyPublisher() }
|
||||
relayConnectivity: @escaping @MainActor () -> AnyPublisher<Bool, Never> = { Just(false).eraseToAnyPublisher() },
|
||||
envelopeRetryQueue: NostrPrivateEnvelopeRetryQueue? = nil
|
||||
) -> NostrTransport.Dependencies {
|
||||
NostrTransport.Dependencies(
|
||||
notificationCenter: notificationCenter,
|
||||
@@ -430,10 +1014,11 @@ struct NostrTransportTests {
|
||||
favoriteStatusForNoiseKey: favoriteStatusForNoiseKey,
|
||||
favoriteStatusForPeerID: favoriteStatusForPeerID,
|
||||
currentIdentity: currentIdentity,
|
||||
registerPendingGiftWrap: registerPendingGiftWrap,
|
||||
sendEvent: sendEvent,
|
||||
registerPendingPrivateEnvelope: registerPendingPrivateEnvelope,
|
||||
sendPrivateEnvelopeBatch: sendPrivateEnvelopeBatch,
|
||||
scheduleAfter: scheduleAfter,
|
||||
relayConnectivity: relayConnectivity
|
||||
relayConnectivity: relayConnectivity,
|
||||
envelopeRetryQueue: envelopeRetryQueue
|
||||
)
|
||||
}
|
||||
|
||||
@@ -457,8 +1042,8 @@ struct NostrTransportTests {
|
||||
from event: NostrEvent,
|
||||
recipient: NostrIdentity
|
||||
) throws -> (packet: BitchatPacket, payload: NoisePayload, senderPubkey: String) {
|
||||
let (content, senderPubkey, _) = try NostrProtocol.decryptPrivateMessage(
|
||||
giftWrap: event,
|
||||
let (content, senderPubkey, _) = try NostrProtocol.decryptPrivateEnvelope(
|
||||
envelope: event,
|
||||
recipientIdentity: recipient
|
||||
)
|
||||
guard content.hasPrefix("bitchat1:") else {
|
||||
@@ -488,6 +1073,17 @@ private enum NostrTransportTestError: Error {
|
||||
case invalidPrivateMessage
|
||||
}
|
||||
|
||||
@MainActor
|
||||
private final class NostrTransportEventProbe: TransportEventDelegate {
|
||||
private(set) var failedMessageIDs: [String] = []
|
||||
|
||||
func didReceiveTransportEvent(_ event: TransportEvent) {
|
||||
guard case .messageDeliveryStatusUpdated(let messageID, let status) = event,
|
||||
case .failed = status else { return }
|
||||
failedMessageIDs.append(messageID)
|
||||
}
|
||||
}
|
||||
|
||||
private func base64URLDecode(_ string: String) -> Data? {
|
||||
var candidate = string
|
||||
let padding = (4 - (candidate.count % 4)) % 4
|
||||
@@ -503,7 +1099,7 @@ private func base64URLDecode(_ string: String) -> Data? {
|
||||
private final class NostrTransportProbe: @unchecked Sendable {
|
||||
private let lock = NSLock()
|
||||
private var sentEventsStorage: [NostrEvent] = []
|
||||
private var pendingGiftWrapIDsStorage: [String] = []
|
||||
private var pendingPrivateEnvelopeIDsStorage: [String] = []
|
||||
private var scheduledActionsStorage: [(@Sendable () -> Void)] = []
|
||||
|
||||
var sentEvents: [NostrEvent] {
|
||||
@@ -512,10 +1108,10 @@ private final class NostrTransportProbe: @unchecked Sendable {
|
||||
return sentEventsStorage
|
||||
}
|
||||
|
||||
var pendingGiftWrapIDs: [String] {
|
||||
var pendingPrivateEnvelopeIDs: [String] {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
return pendingGiftWrapIDsStorage
|
||||
return pendingPrivateEnvelopeIDsStorage
|
||||
}
|
||||
|
||||
var scheduledActionCount: Int {
|
||||
@@ -524,15 +1120,16 @@ private final class NostrTransportProbe: @unchecked Sendable {
|
||||
return scheduledActionsStorage.count
|
||||
}
|
||||
|
||||
func record(event: NostrEvent) {
|
||||
func record(batch: [NostrEvent]) -> Bool {
|
||||
lock.lock()
|
||||
sentEventsStorage.append(event)
|
||||
sentEventsStorage.append(contentsOf: batch)
|
||||
lock.unlock()
|
||||
return true
|
||||
}
|
||||
|
||||
func recordPendingGiftWrap(id: String) {
|
||||
func recordPendingPrivateEnvelope(id: String) {
|
||||
lock.lock()
|
||||
pendingGiftWrapIDsStorage.append(id)
|
||||
pendingPrivateEnvelopeIDsStorage.append(id)
|
||||
lock.unlock()
|
||||
}
|
||||
|
||||
|
||||
@@ -1,130 +0,0 @@
|
||||
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,15 +56,12 @@ 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,
|
||||
hidePreviewsProvider: { false }
|
||||
requestDeliverer: deliverer
|
||||
)
|
||||
let peerID = PeerID(str: "deadbeefdeadbeef")
|
||||
|
||||
@@ -77,27 +74,6 @@ 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 = TestConstants.settleTimeout,
|
||||
timeout: TimeInterval = 1.0,
|
||||
condition: @escaping () -> Bool
|
||||
) async -> Bool {
|
||||
let deadline = Date().addingTimeInterval(timeout)
|
||||
|
||||
@@ -320,7 +320,7 @@ struct SecureIdentityStateManagerVouchTests {
|
||||
// MARK: - Helpers
|
||||
|
||||
private func waitUntil(
|
||||
timeout: TimeInterval = TestConstants.settleTimeout,
|
||||
timeout: TimeInterval = 1.0,
|
||||
condition: @escaping () -> Bool
|
||||
) async -> Bool {
|
||||
let deadline = Date().addingTimeInterval(timeout)
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
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.settleTimeout)
|
||||
try await TestHelpers.waitFor({ delegate.packets.count == 1 }, timeout: TestConstants.shortTimeout)
|
||||
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.settleTimeout)
|
||||
try await TestHelpers.waitFor({ delegate.packets.count == 1 }, timeout: TestConstants.shortTimeout)
|
||||
#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 = TestConstants.settleTimeout,
|
||||
timeout: TimeInterval = 1.0,
|
||||
condition: @escaping () -> Bool
|
||||
) async -> Bool {
|
||||
let deadline = Date().addingTimeInterval(timeout)
|
||||
|
||||
@@ -11,54 +11,14 @@ 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"
|
||||
|
||||
@@ -1,177 +0,0 @@
|
||||
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,103 +554,6 @@ 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(TestConstants.settleTimeout))
|
||||
let deadline = ContinuousClock.now.advanced(by: .seconds(5))
|
||||
while !condition(), ContinuousClock.now < deadline {
|
||||
await Task.yield()
|
||||
try? await Task.sleep(nanoseconds: 1_000_000)
|
||||
|
||||
@@ -59,24 +59,11 @@ 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(TestConstants.settleTimeout))
|
||||
let deadline = ContinuousClock.now.advanced(by: .seconds(5))
|
||||
while !condition(), ContinuousClock.now < deadline {
|
||||
await Task.yield()
|
||||
try? await Task.sleep(nanoseconds: 1_000_000)
|
||||
|
||||
@@ -13,16 +13,17 @@ 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 {}
|
||||
|
||||
@@ -31,28 +32,14 @@ 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()
|
||||
}
|
||||
@@ -155,38 +142,26 @@ 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 let enteredGate = DispatchSemaphore(value: 0)
|
||||
private var _entered = false
|
||||
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
|
||||
@@ -206,6 +181,18 @@ 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) }
|
||||
@@ -223,7 +210,7 @@ struct VoiceRecorderTests {
|
||||
let owner = VoiceRecorder.RecordingOwner()
|
||||
|
||||
let startTask = Task { try await voiceRecorder.startRecording(owner: owner) }
|
||||
#expect(await session.waitUntilActivationBegan())
|
||||
await waitUntil { session.activationBegan }
|
||||
|
||||
await voiceRecorder.cancelRecording(owner: owner)
|
||||
session.resumeActivation()
|
||||
@@ -321,7 +308,7 @@ struct VoiceRecorderTests {
|
||||
try await finishingHold.start()
|
||||
let firstURL = try #require(factory.urls.first)
|
||||
let finishTask = Task { await finishingHold.finish() }
|
||||
#expect(await paddingGate.waitUntilEntered())
|
||||
await waitUntil { paddingGate.entered }
|
||||
|
||||
await #expect(throws: VoiceRecorder.RecorderError.recordingInProgress) {
|
||||
try await rejectedHold.start()
|
||||
|
||||
+37
-43
@@ -1,53 +1,47 @@
|
||||
# Tor integration
|
||||
Tor-by-default integration (scaffold)
|
||||
|
||||
## Overview
|
||||
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.
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
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`.
|
||||
Artifact maintenance
|
||||
- Binary provenance, rebuild steps, and current hashes are documented in `docs/ARTI-BINARY-PROVENANCE.md`.
|
||||
- The xcframework must include iOS device, iOS simulator, and macOS arm64 slices.
|
||||
- Any refresh reviews the Rust source, `Cargo.lock`, generated header, build script, and new hashes together. A binary-only update is not acceptable.
|
||||
- Any refresh should review the Rust source, `Cargo.lock`, generated header, build script, and new hashes together.
|
||||
|
||||
## Known gap: no bridges or pluggable transports
|
||||
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.
|
||||
|
||||
`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.
|
||||
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.
|
||||
|
||||
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.
|
||||
torrc template
|
||||
The generated torrc (under Application Support/bitchat/tor/torrc) is:
|
||||
|
||||
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.
|
||||
DataDirectory <AppSupport>/bitchat/tor
|
||||
ClientOnly 1
|
||||
SOCKSPort 127.0.0.1:39050
|
||||
ControlPort 127.0.0.1:39051
|
||||
CookieAuthentication 1
|
||||
AvoidDiskWrites 1
|
||||
MaxClientCircuitsPending 8
|
||||
|
||||
## Dev bypass (local only)
|
||||
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.
|
||||
|
||||
Define the Swift compiler flag `BITCHAT_DEV_ALLOW_CLEARNET` to allow direct network access without Tor while developing. Never enable it in release builds.
|
||||
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.
|
||||
|
||||
@@ -1,94 +0,0 @@
|
||||
# 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,7 +18,6 @@ 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
|
||||
|
||||
@@ -29,9 +28,7 @@ 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 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.
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
@@ -48,10 +45,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 6 hours so gossip sync survives a relaunch and can cross mesh partitions.
|
||||
- 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.
|
||||
- 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, 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.
|
||||
- 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.
|
||||
|
||||
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.
|
||||
|
||||
@@ -63,9 +60,6 @@ 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
|
||||
@@ -92,24 +86,9 @@ 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, 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.
|
||||
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.
|
||||
|
||||
## Release Review Checklist
|
||||
|
||||
@@ -118,4 +97,3 @@ 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,15 +48,6 @@ 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() } }
|
||||
@@ -84,10 +75,6 @@ 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
|
||||
@@ -109,7 +96,6 @@ 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
|
||||
@@ -272,46 +258,26 @@ 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(generation: generation)
|
||||
await self?.bootstrapPollLoop()
|
||||
}
|
||||
}
|
||||
|
||||
private func bootstrapPollLoop(generation: Int) async {
|
||||
private func bootstrapPollLoop() 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()
|
||||
|
||||
self.bootstrapProgress = progress
|
||||
self.bootstrapSummary = summary
|
||||
if progress >= 100 { self.isStarting = false }
|
||||
self.recomputeReady()
|
||||
|
||||
if progress >= 100 {
|
||||
didComplete = true
|
||||
break
|
||||
await MainActor.run {
|
||||
self.bootstrapProgress = progress
|
||||
self.bootstrapSummary = summary
|
||||
if progress >= 100 { self.isStarting = false }
|
||||
self.recomputeReady()
|
||||
}
|
||||
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)
|
||||
if progress >= 100 { break }
|
||||
try? await Task.sleep(nanoseconds: 1_000_000_000)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -357,7 +323,6 @@ 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
|
||||
@@ -367,7 +332,6 @@ 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 }
|
||||
@@ -405,13 +369,11 @@ 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,7 +5,4 @@ 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