Skip to main content

vector_core/community/v2/
streamauth.rs

1//! Concord v2 stream-key NIP-42 authentication.
2//!
3//! Every v2 plane is kind-1059 traffic addressed to a DERIVED per-stream pubkey
4//! (control, guestbook, per-channel chat, rekey, dissolved) — never the user's
5//! own identity. Relays that gate kind 1059 behind NIP-42 (ditto-relay's default
6//! `AUTH_KINDS=4,1059`) require that EVERY `authors` entry in a kind-1059 REQ be
7//! an authenticated pubkey on the connection, and reply
8//! `CLOSED auth-required: all authors must be authenticated` otherwise. The
9//! user's login can't satisfy that — the stream address isn't their pubkey — so
10//! an unauthenticated client reads back ZERO events and a join's control-plane
11//! verify (or any community fetch) fails closed.
12//!
13//! The fix (mirroring Armada's `streamAuth`): the client HOLDS the stream secret
14//! keys (derived from the `community_root` / channel keys it already stores), so
15//! it can NIP-42-authenticate AS each stream by signing an extra kind-22242 AUTH
16//! event per stream against the relay's challenge. This module is the registry
17//! of stream keys the client currently holds plus the challenge responder; the
18//! connection ends up authenticated as the user AND every stream it will query.
19//!
20//! Signing is local (raw derived keys) — it never touches the account signer /
21//! bunker.
22
23use nostr_sdk::prelude::IntoEventBuilder;
24use crate::event_ext::FinalizeOnClock;
25use std::collections::HashMap;
26use std::sync::atomic::{AtomicBool, Ordering};
27use std::sync::{LazyLock, Mutex};
28
29use nostr_sdk::prelude::{Client, ClientAuthentication, ClientMessage, ClientNotification, Keys, RelayUrl, StreamExt};
30
31use super::community::CommunityV2;
32
33/// stream pubkey (x-only bytes) → the derived Keys that authenticate it.
34static REGISTRY: LazyLock<Mutex<HashMap<[u8; 32], Keys>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
35/// Whether the persistent challenge responder is running this session (idempotent spawn).
36static RESPONDER_RUNNING: AtomicBool = AtomicBool::new(false);
37/// Each relay's last NIP-42 challenge. A challenge stays valid for the connection
38/// lifetime, and a gating relay issues it ONCE (on the first gated REQ) — so keys
39/// registered AFTER that frame can only authenticate by replaying the remembered
40/// challenge; waiting for a fresh one would wait forever, and one unauthenticated
41/// author fails a whole REQ's gate. A stale entry (relay reconnected since) is
42/// harmless: the relay ignores it and the next gated REQ re-challenges.
43static CHALLENGES: LazyLock<Mutex<HashMap<RelayUrl, String>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
44
45/// Register a batch of stream keys (idempotent). Returns how many were NEW.
46pub fn register(keys: impl IntoIterator<Item = Keys>) -> usize {
47    let mut reg = REGISTRY.lock().unwrap_or_else(|e| e.into_inner());
48    let mut added = 0;
49    for k in keys {
50        if reg.insert(k.public_key().to_bytes(), k).is_none() {
51            added += 1;
52        }
53    }
54    added
55}
56
57/// Register every plane a community currently exposes: control, guestbook, the
58/// dissolved plane, and each readable channel's Chat Plane (a keyless private
59/// channel has no readable plane yet, so it's skipped — its rekey plane keys up
60/// first). Called at join and on every follow so a rotated address is covered.
61pub fn register_community(c: &CommunityV2) -> usize {
62    let mut keys: Vec<Keys> = vec![
63        super::derive::guestbook_group_key(&c.community_root, c.id(), c.root_epoch).keys().clone(),
64        super::derive::dissolved_group_key(c.id()).keys().clone(),
65    ];
66    // The Control Plane's signer: the whole legacy key on a pre-split epoch, the
67    // staff-held control_root's signer when this member holds it. A non-staff
68    // member on a split epoch holds NO secret for the plane address (CORD-02
69    // §2), so there is nothing to authenticate AS — a NIP-42 read-gating relay
70    // must not gate reads on a write-restricted stream's key, and registering
71    // nothing here is what keeps the auth dance from waiting on an
72    // unanswerable challenge.
73    if let Some(k) = super::control::ControlPlane::of(c).signer_keys() {
74        keys.push(k.clone());
75    }
76    for ch in &c.channels {
77        if ch.private && ch.key.is_none() {
78            continue;
79        }
80        let (secret, epoch) = c.channel_secret(ch);
81        keys.push(super::derive::channel_group_key(&secret, &ch.id, epoch).keys().clone());
82        // A writer authenticates as its address; a reader holds no key for it.
83        if let Some((_, _, writer)) = super::service::live_writer_of(c, ch) {
84            keys.push(writer.keys().clone());
85        }
86    }
87    // The next-epoch rekey planes we subscribe to (base + each private channel).
88    for pk_keys in rekey_plane_keys(c) {
89        keys.push(pk_keys);
90    }
91    register(keys)
92}
93
94/// The rekey-plane Keys a community watches (base next-epoch + each private
95/// channel's next-epoch), mirroring `realtime::rekey_authors` so an AUTH-gating
96/// relay serves the rotation crates too.
97///
98/// Channel planes fan across the SAME addressing roots `follow_rekeys` queries
99/// (current + archived priors, CORD-06 D2 — a removal-forced channel rekey
100/// rides the PRIOR root). Registration must be UPFRONT and complete: a gating
101/// relay issues its NIP-42 challenge once per connection, so a key registered
102/// after the connection authed can never authenticate — a current-root-only
103/// registration left the prior-root crate plane CLOSED and wedged the channel
104/// at its old epoch while the base advanced.
105fn rekey_plane_keys(c: &CommunityV2) -> Vec<Keys> {
106    use crate::community::Epoch;
107    let mut out = vec![super::derive::base_rekey_group_key(&c.community_root, c.id(), Epoch(c.root_epoch.0.saturating_add(1))).keys().clone()];
108    let cid_hex = crate::simd::hex::bytes_to_hex_32(&c.id().0);
109    let roots = super::service::channel_rekey_addressing_roots(c.community_root, &cid_hex);
110    for ch in &c.channels {
111        if ch.private {
112            for root in &roots {
113                out.push(super::derive::channel_rekey_group_key(root, &ch.id, Epoch(ch.epoch.0.saturating_add(1))).keys().clone());
114            }
115        }
116    }
117    out
118}
119
120/// Record a relay's challenge, returning true when its VALUE changed — a new
121/// value means a new connection (NIP-42 challenges live for one connection), so
122/// any sub REQ the pool re-applied before this auth was gate-CLOSED and needs a
123/// re-send. A re-delivered identical challenge is the same connection: auth is
124/// re-sent (idempotent) but no resubscribe is triggered.
125fn remember_challenge(relay: &RelayUrl, challenge: &str) -> bool {
126    CHALLENGES
127        .lock()
128        .unwrap_or_else(|e| e.into_inner())
129        .insert(relay.clone(), challenge.to_string())
130        .as_deref()
131        != Some(challenge)
132}
133
134/// Whether the relay has sent this process an AUTH challenge, which Vector answers as the user.
135pub fn challenged(relay_url: &str) -> bool {
136    let want = crate::inbox_relays::normalize_relay_url(relay_url);
137    CHALLENGES.lock().unwrap_or_else(|e| e.into_inner()).keys().any(|r| crate::inbox_relays::normalize_relay_url(r.as_str()) == want)
138}
139
140#[cfg(test)]
141pub(crate) fn note_challenge(relay_url: &str) {
142    remember_challenge(&RelayUrl::parse(relay_url).unwrap(), "test");
143}
144
145/// The challenge this relay's connection last issued, if seen.
146fn remembered_challenge(relay: &RelayUrl) -> Option<String> {
147    CHALLENGES.lock().unwrap_or_else(|e| e.into_inner()).get(relay).cloned()
148}
149
150/// Last responder-driven resubscribe per relay, bounding the challenge→auth→
151/// resubscribe reaction to one per [`RESUB_COOLDOWN`] window per relay.
152static RESUB_AT: LazyLock<Mutex<HashMap<RelayUrl, web_time::Instant>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
153const RESUB_COOLDOWN: std::time::Duration = std::time::Duration::from_secs(30);
154
155/// True (and stamps now) if this relay hasn't been resubscribed within the
156/// cooldown window; false while one is still fresh.
157fn resub_cooldown_elapsed(relay: &RelayUrl) -> bool {
158    let mut map = RESUB_AT.lock().unwrap_or_else(|e| e.into_inner());
159    let now = web_time::Instant::now();
160    match map.get(relay) {
161        Some(at) if now.duration_since(*at) < RESUB_COOLDOWN => false,
162        _ => {
163            map.insert(relay.clone(), now);
164            true
165        }
166    }
167}
168
169/// Forget every registered stream key (on session swap). The responder task
170/// exits on its own once the registry it serves is empty.
171pub fn clear() {
172    // Replaced, not cleared: a cleared table keeps its peak allocation.
173    *REGISTRY.lock().unwrap_or_else(|e| e.into_inner()) = HashMap::new();
174    *CHALLENGES.lock().unwrap_or_else(|e| e.into_inner()) = HashMap::new();
175    *RESUB_AT.lock().unwrap_or_else(|e| e.into_inner()) = HashMap::new();
176    RESPONDER_RUNNING.store(false, Ordering::SeqCst);
177}
178
179/// Whether we hold any stream keys (skip the whole dance when not).
180pub fn is_empty() -> bool {
181    REGISTRY.lock().unwrap_or_else(|e| e.into_inner()).is_empty()
182}
183
184/// Sign a NIP-42 AUTH (kind-22242) event for EVERY registered stream key against
185/// `challenge` + `relay`. Local raw-key signing; a malformed key is skipped.
186fn sign_all(challenge: &str, relay: &RelayUrl) -> Vec<nostr_sdk::prelude::Event> {
187    let reg = REGISTRY.lock().unwrap_or_else(|e| e.into_inner());
188    reg.values()
189        .filter_map(|keys| ClientAuthentication::new(challenge, relay.clone()).into_event_builder().finalize_on_clock(keys).ok())
190        .collect()
191}
192
193/// Authenticate every registered stream key on `relay` against `challenge`. Each
194/// rides a NIP-42 `AUTH` client message (NOT an `EVENT` publish — relays reject a
195/// bare kind-22242 event). Best-effort per key. Returns how many were sent.
196async fn authenticate_streams(client: &Client, relay: &RelayUrl, challenge: &str) -> usize {
197    let events = sign_all(challenge, relay);
198    let Ok(Some(r)) = client.relay(relay.clone()).await else {
199        return 0;
200    };
201    let mut sent = 0;
202    for ev in events {
203        if r.send_msg(ClientMessage::auth(ev)).await.is_ok() {
204            sent += 1;
205        }
206    }
207    sent
208}
209
210/// Ensure the persistent stream-AUTH responder is running for this session
211/// (idempotent). It watches the client's notification stream and, on EVERY relay
212/// AUTH challenge, authenticates as all registered stream keys on that relay.
213///
214/// AUTH-gating relays (Ditto) challenge on the GATED REQ — not on connect — and
215/// nostr-sdk retries the REQ after auth, so once this responder is running a
216/// normal community fetch/subscribe just works: the REQ triggers the challenge,
217/// this answers it with the stream keys, and the retry reads the plane. The
218/// user's own login rides nostr-sdk's built-in auto-auth. Exits on session swap.
219pub fn ensure_responder(client: &Client) {
220    if RESPONDER_RUNNING.swap(true, Ordering::SeqCst) {
221        return; // already running this session
222    }
223    let client = client.clone();
224    crate::db::spawn_bound(async move {
225        let mut notifications = client.notifications();
226        while let Some(n) = notifications.next().await {
227            if let ClientNotification::Message { relay_url, message } = n {
228                if let nostr_sdk::prelude::RelayMessage::Auth { challenge } = *message {
229                    let challenge = challenge.into_owned();
230                    // This relay gates reads behind NIP-42 (the boot volley routes fallbacks by
231                    // it), refreshed at most daily so a challenge-spamming relay can't drive writes.
232                    crate::community::transport::note_auth_gate(relay_url.as_str());
233                    let fresh_connection = remember_challenge(&relay_url, &challenge);
234                    if !is_empty() {
235                        authenticate_streams(&client, &relay_url, &challenge).await;
236                        // A NEW challenge value means a new connection — the pool's
237                        // re-applied sub REQ raced this auth and got gate-CLOSED, and
238                        // the relay won't challenge again. Re-send our subs now that
239                        // the streams are authenticated. Cooldown-bounded so a relay
240                        // minting endless challenges can't drive a resubscribe loop.
241                        if fresh_connection && resub_cooldown_elapsed(&relay_url) {
242                            super::realtime::resubscribe_relay(&client, &relay_url).await;
243                        }
244                    }
245                }
246            }
247        }
248        RESPONDER_RUNNING.store(false, Ordering::SeqCst);
249    });
250}
251
252/// Prepare gated relays for an imminent fetch: make sure the community's stream
253/// keys are registered and the responder is live, so the fetch's REQ-triggered
254/// challenge is answered. A no-op when no client is connected (offline tests).
255pub fn prime(community: &CommunityV2) {
256    register_community(community);
257    if let Some(client) = crate::state::nostr_client() {
258        ensure_responder(&client);
259    }
260}
261
262/// Prime the connection AUTH on `relays` before a live subscription: a
263/// subscription (unlike a fetch) isn't auto-retried after the AUTH gate, so the
264/// socket must already be authenticated as EVERY stream the sub's `authors` will
265/// name — one unauthenticated key fails the whole REQ. Two passes:
266///
267/// 1. Replay each relay's REMEMBERED challenge for all registered keys — a gating
268///    relay challenges once per connection, so keys registered after that frame
269///    (a control fold that revealed new channels) would otherwise never auth.
270/// 2. A cheap gated fetch, which on a fresh/reconnected socket triggers the
271///    challenge the responder answers (and nostr-sdk retries the fetch after).
272///
273/// No-op with no registered keys / no relays.
274pub async fn prime_auth(client: &Client, relays: &[String]) {
275    if is_empty() || relays.is_empty() {
276        return;
277    }
278    ensure_responder(client);
279    let urls: Vec<RelayUrl> = relays.iter().filter_map(|r| RelayUrl::parse(r).ok()).collect();
280    if urls.is_empty() {
281        return;
282    }
283    for url in &urls {
284        if let Some(challenge) = remembered_challenge(url) {
285            authenticate_streams(client, url, &challenge).await;
286        }
287    }
288    let authors: Vec<nostr_sdk::prelude::PublicKey> = {
289        let reg = REGISTRY.lock().unwrap_or_else(|e| e.into_inner());
290        reg.keys().filter_map(|pk| nostr_sdk::prelude::PublicKey::from_slice(pk).ok()).collect()
291    };
292    if authors.is_empty() {
293        return;
294    }
295    let filter = nostr_sdk::prelude::Filter::new()
296        .kind(nostr_sdk::prelude::Kind::Custom(super::stream::KIND_WRAP))
297        .authors(authors)
298        .limit(1);
299    // Bounded so a dead relay can't stall the subscription refresh behind it.
300    let budget = crate::relay_request_timeout(std::time::Duration::from_secs(6));
301    let _ = crate::rt::time::timeout(budget + std::time::Duration::from_secs(2), client
302        .fetch_events(nostr_sdk::prelude::ReqTarget::manual(
303            urls.into_iter().map(|u| (u, vec![filter.clone()])),
304        ))
305        .timeout(budget)).await;
306}
307
308#[cfg(test)]
309mod tests {
310    use super::*;
311    use crate::community::v2::control::{genesis, CommunityMetadata};
312    use crate::community::v2::community::{ChannelV2, CommunityV2};
313    use crate::community::{ChannelId, Epoch};
314    use nostr_sdk::prelude::Keys;
315
316    /// A community with one public, one keyed-private, and one KEYLESS-private
317    /// channel — the three registration classes.
318    fn community_with_channel_mix() -> CommunityV2 {
319        let owner = Keys::generate();
320        let g = genesis(&owner, CommunityMetadata { name: "auth-test".into(), ..Default::default() }, 1_000).unwrap();
321        let mut c = CommunityV2::from_genesis(&g, "auth-test", None, vec!["wss://gated.example".into()], 0);
322        c.channels.push(ChannelV2 { id: ChannelId([2u8; 32]), name: "keyed-private".into(), private: true, key: Some([7u8; 32]), epoch: Epoch(3), voice: None, meta_custom: None, meta_extra: Default::default(), writers: None, sealed: None });
323        c.channels.push(ChannelV2 { id: ChannelId([3u8; 32]), name: "keyless-private".into(), private: true, key: None, epoch: Epoch(0), voice: None, meta_custom: None, meta_extra: Default::default(), writers: None, sealed: None });
324        c
325    }
326
327    fn registered(pk: &nostr_sdk::prelude::PublicKey) -> bool {
328        REGISTRY.lock().unwrap_or_else(|e| e.into_inner()).contains_key(&pk.to_bytes())
329    }
330
331    /// The registry covers every plane a member must authenticate AS — and a
332    /// keyless private channel (no readable plane yet) is skipped, while its
333    /// NEXT-epoch rekey plane (the entry point for its key) is covered.
334    #[test]
335    fn register_community_covers_planes_and_skips_keyless() {
336        let c = community_with_channel_mix();
337        let added = register_community(&c);
338        assert!(added >= 6, "control+guestbook+dissolved+public chat+keyed chat+rekeys = at least 6 new keys, got {added}");
339
340        use super::super::derive;
341        // The control SIGNER registers (this community's owner holds the
342        // control_root); the legacy derivation is not the address and must not.
343        assert!(registered(&super::super::control::ControlPlane::of(&c).pk()));
344        assert!(!registered(&derive::control_group_key(&c.community_root, c.id(), c.root_epoch).pk()));
345        assert!(registered(&derive::guestbook_group_key(&c.community_root, c.id(), c.root_epoch).pk()));
346        assert!(registered(&derive::dissolved_group_key(c.id()).pk()));
347        // Public channel: chat plane derives from the community root.
348        let public = &c.channels[0];
349        let (secret, epoch) = c.channel_secret(public);
350        assert!(registered(&derive::channel_group_key(&secret, &public.id, epoch).pk()));
351        // Keyed private channel: chat plane derives from its own key + epoch.
352        let keyed = &c.channels[1];
353        assert!(registered(&derive::channel_group_key(&[7u8; 32], &keyed.id, Epoch(3)).pk()));
354        // KEYLESS private channel: no readable plane — deriving from the root
355        // would address the PUBLIC plane, so it must NOT be registered.
356        let keyless = &c.channels[2];
357        assert!(!registered(&derive::channel_group_key(&c.community_root, &keyless.id, Epoch(0)).pk()));
358        // Rekey planes: base next-epoch + each PRIVATE channel's next-epoch.
359        assert!(registered(&derive::base_rekey_group_key(&c.community_root, c.id(), Epoch(c.root_epoch.0 + 1)).pk()));
360        assert!(registered(&derive::channel_rekey_group_key(&c.community_root, &keyed.id, Epoch(4)).pk()));
361
362        // Idempotent: a second registration adds nothing.
363        assert_eq!(register_community(&c), 0);
364    }
365
366    /// The PIECE-2 regression: a key registered AFTER the connection's one
367    /// challenge was consumed still authenticates, because the challenge is
368    /// remembered and `sign_all` covers every CURRENTLY-registered key.
369    #[test]
370    fn late_registered_keys_sign_against_the_remembered_challenge() {
371        let relay = RelayUrl::parse("wss://late-keys.example").unwrap();
372        let early = Keys::generate();
373        register([early.clone()]);
374        // The connection's single challenge arrives while only `early` exists.
375        assert!(remember_challenge(&relay, "challenge-1"), "first sighting is a fresh connection");
376        // A control fold reveals a new channel → its plane key registers late.
377        let late = Keys::generate();
378        register([late.clone()]);
379        // The replay path (prime_auth pass 1) must sign for BOTH keys.
380        let challenge = remembered_challenge(&relay).expect("challenge was remembered");
381        let events = sign_all(&challenge, &relay);
382        let signers: Vec<_> = events.iter().map(|e| e.pubkey).collect();
383        assert!(signers.contains(&early.public_key()));
384        assert!(signers.contains(&late.public_key()));
385    }
386
387    /// AUTH events must be NIP-42-shaped: kind 22242, challenge + relay tags,
388    /// valid signature by the stream key.
389    #[test]
390    fn signed_auth_events_are_nip42_shaped() {
391        let relay = RelayUrl::parse("wss://shape.example").unwrap();
392        let key = Keys::generate();
393        register([key.clone()]);
394        let events = sign_all("shape-challenge", &relay);
395        let ev = events.iter().find(|e| e.pubkey == key.public_key()).expect("signed by the registered key");
396        assert_eq!(ev.kind, nostr_sdk::prelude::Kind::Authentication);
397        assert!(ev.verify().is_ok(), "signature + id must verify");
398        let tag_values: Vec<String> = ev.tags.iter().filter_map(|t| t.content().map(String::from)).collect();
399        assert!(tag_values.iter().any(|v| v == "shape-challenge"), "carries the challenge tag");
400    }
401
402    /// A NEW challenge value = a new connection (triggers the resubscribe); the
403    /// SAME value re-delivered = the same connection (auth only, no resubscribe).
404    #[test]
405    fn challenge_value_change_detects_a_new_connection() {
406        let relay = RelayUrl::parse("wss://conn-detect.example").unwrap();
407        assert!(remember_challenge(&relay, "c1"), "first sighting");
408        assert!(!remember_challenge(&relay, "c1"), "same value = same connection");
409        assert!(remember_challenge(&relay, "c2"), "new value = reconnected");
410        assert_eq!(remembered_challenge(&relay).as_deref(), Some("c2"), "memory holds the newest");
411    }
412
413    /// The responder-driven resubscribe is cooldown-bounded per relay, so a
414    /// relay minting endless fresh challenges can't drive a resubscribe loop.
415    #[test]
416    fn resubscribe_cooldown_bounds_the_reaction() {
417        let relay = RelayUrl::parse("wss://cooldown.example").unwrap();
418        assert!(resub_cooldown_elapsed(&relay), "first trigger passes");
419        assert!(!resub_cooldown_elapsed(&relay), "immediate repeat is suppressed");
420        let other = RelayUrl::parse("wss://cooldown-other.example").unwrap();
421        assert!(resub_cooldown_elapsed(&other), "cooldown is per-relay");
422    }
423}