engawa-chat 0.6.0

A peer-to-peer chat lobby for editors and browsers
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
//! Seed discovery for explicit participation in the default public lobby only.
//! NIP-01 ephemeral events carry a route, never a gossip packet or an invite.

use std::{collections::HashMap, time::Duration};

use anyhow::{Context, Result, bail};
use futures_util::{StreamExt, future::join_all};
use iroh::{Endpoint, EndpointAddr, EndpointId, RelayUrl, SecretKey, Signature, Watcher};
use n0_future::time::{self, Instant};
use nostr_sdk::prelude::{
    Event, EventBuilder, Filter, FinalizeEvent, Keys, Kind, PublicKey, Relay, RelayLimits,
    RelayMessage, RelayNotification, RelayOptions, RelayUrl as NostrUrl, Tag, Timestamp,
};
use serde::{Deserialize, Serialize};
use tokio::sync::mpsc;

const KIND: Kind = Kind::Custom(20978);
#[cfg(not(feature = "rendezvous-test"))]
const TOPIC: &str = "engawa-public-rendezvous-v1";
#[cfg(feature = "rendezvous-test")]
const TOPIC: &str = "engawa-public-rendezvous-test-v1";
const TTL: u64 = 90;
const FUTURE_SKEW: u64 = 10;
const HEARTBEAT: Duration = Duration::from_secs(40);
const IO_TIMEOUT: Duration = Duration::from_secs(10);
const MAX_PEERS: usize = 64;

#[derive(Debug)]
pub(crate) enum Update {
    Peer(EndpointAddr),
    /// At least one service both accepted our subscription and acknowledged our presence.
    Available(bool),
}

#[cfg(not(feature = "rendezvous-test"))]
fn relay_urls() -> Vec<NostrUrl> {
    ["wss://relay.damus.io", "wss://nos.lol"]
        .map(|s| NostrUrl::parse(s).expect("fixed Nostr relay URL"))
        .into()
}

#[cfg(feature = "rendezvous-test")]
fn relay_urls() -> Vec<NostrUrl> {
    // A fixture build cannot fall back to public relays, even if misconfigured.
    option_env!("ENGAWA_TEST_NOSTR_RELAY")
        .and_then(|s| url::Url::parse(s).ok())
        .filter(|u| u.scheme() == "ws" && u.host_str() == Some("127.0.0.1"))
        .and_then(|u| NostrUrl::parse(u.as_str()).ok())
        .into_iter()
        .collect()
}

#[derive(Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
struct Presence<'a> {
    peer: &'a str,
    relay: &'a str,
    proof: &'a str,
}

fn challenge(author: &PublicKey, stamp: u64, relay: &str) -> blake3::Hash {
    // Fixed-width fields precede the final variable-length field. Bind the Nostr author
    // so another publisher cannot reuse a signed endpoint as its own. TOPIC separates fixtures.
    let mut h = blake3::Hasher::new_derive_key(TOPIC);
    h.update(author.as_bytes());
    h.update(&stamp.to_be_bytes());
    h.update(relay.as_bytes());
    h.finalize()
}

fn announcement(key: &SecretKey, signer: &Keys, home: &RelayUrl, stamp: u64) -> Result<Event> {
    let proof = key.sign(challenge(&signer.public_key(), stamp, home.as_str()).as_bytes());
    let content = serde_json::to_string(&Presence {
        peer: &hex::encode(key.public().as_bytes()),
        relay: home.as_str(),
        proof: &hex::encode(proof.to_bytes()),
    })?;
    Ok(EventBuilder::new(KIND, content)
        .tag(Tag::hashtag(TOPIC))
        .custom_created_at(Timestamp::from_secs(stamp))
        .finalize(signer)?)
}

fn decode_hex<const N: usize>(text: &str) -> Option<[u8; N]> {
    if text.len() != 2 * N || text.bytes().any(|b| b.is_ascii_uppercase()) {
        return None;
    }
    let mut bytes = [0; N];
    hex::decode_to_slice(text, &mut bytes).ok()?;
    Some(bytes)
}

// The SDK verifies the NIP-01 id and Schnorr signature before emitting RelayNotification::Event.
// This second (iroh) signature authenticates possession of the advertised endpoint's key.
fn open_presence(
    event: &Event,
    me: EndpointId,
    homes: &[RelayUrl],
    now: u64,
) -> Option<EndpointAddr> {
    let stamp = event.created_at.as_secs();
    if event.kind != KIND
        || event.tags.len() != 1
        || event.tags[0].as_slice() != ["t", TOPIC]
        || event.content.len() > 512
        || stamp > now.saturating_add(FUTURE_SKEW)
        || now.saturating_sub(stamp) >= TTL
    {
        return None;
    }
    let presence: Presence<'_> = serde_json::from_str(&event.content).ok()?;
    // Never parse or dial a caller-supplied URL: select the actual URL from iroh's own map.
    let home = homes.iter().find(|url| url.as_str() == presence.relay)?;
    let id = EndpointId::from_bytes(&decode_hex(presence.peer)?).ok()?;
    if id == me {
        return None;
    }
    let proof = Signature::from_bytes(&decode_hex(presence.proof)?);
    id.verify(
        challenge(&event.pubkey, stamp, home.as_str()).as_bytes(),
        &proof,
    )
    .ok()?;
    Some(EndpointAddr::new(id).with_relay_url(home.clone()))
}

#[derive(Default)]
struct Seen(HashMap<EndpointId, u64>);

impl Seen {
    fn admit(&mut self, peer: EndpointId, stamp: u64, now: u64) -> bool {
        // Cross-relay replay suppression. Never evict a still-valid proof to admit a new id.
        if let Some(last) = self.0.get_mut(&peer) {
            if stamp.saturating_sub(*last) < HEARTBEAT.as_secs() / 2 {
                return false;
            }
            *last = stamp;
            return true;
        }
        if self.0.len() == MAX_PEERS {
            self.0.retain(|_, last| now.saturating_sub(*last) < TTL);
            if self.0.len() == MAX_PEERS {
                return false;
            }
        }
        self.0.insert(peer, stamp);
        true
    }
}

enum Report {
    Peer(EndpointAddr, u64),
    Health(usize, bool),
}

struct Session {
    endpoint: Endpoint,
    signer: Keys,
    homes: Vec<RelayUrl>,
    reports: mpsc::Sender<Report>,
}

impl Session {
    fn publishable_home(&self) -> Option<RelayUrl> {
        self.endpoint
            .home_relay_status()
            .get()
            .iter()
            .find(|s| s.is_connected() && self.homes.contains(s.url()))
            .map(|s| s.url().clone())
    }

    async fn connected(&self, index: usize, url: &NostrUrl) -> Result<()> {
        let mut limits = RelayLimits::default();
        limits.messages.max_size = Some(2048);
        limits.events.max_num_tags = Some(1);
        // A connection has one owner; the SDK shuts down its socket and all subscriptions
        // on last Relay drop, including when the enclosing session future is cancelled.
        let relay = Relay::builder(url.clone())
            .opts(
                RelayOptions::new()
                    .limits(limits)
                    .notification_channel_size(64)
                    .verify_subscriptions(true)
                    .reconnect(false),
            )
            .build();
        relay.try_connect().timeout(IO_TIMEOUT).await?;
        let mut notices = relay.notifications();
        let sub = relay
            .subscribe(Filter::new().kind(KIND).hashtag(TOPIC).limit(0))
            .await?;
        time::timeout(IO_TIMEOUT, async {
            while let Some(n) = notices.next().await {
                if let RelayNotification::Message { message } = n {
                    match *message {
                        RelayMessage::EndOfStoredEvents(id) if *id == sub => return Ok(()),
                        RelayMessage::Closed {
                            subscription_id, ..
                        } if *subscription_id == sub => {
                            bail!("public discovery subscription rejected");
                        }
                        _ => (),
                    }
                }
            }
            bail!("public discovery subscription ended");
        })
        .await??;
        time::timeout(IO_TIMEOUT, self.endpoint.online()).await?;

        let mut tick = time::interval(HEARTBEAT);
        tick.set_missed_tick_behavior(time::MissedTickBehavior::Skip);
        let mut budget = 0;
        let mut reset_at = Instant::now();
        loop {
            tokio::select! {
                _ = tick.tick() => {
                    let home = self.publishable_home().context("no connected official iroh relay")?;
                    let ev = announcement(self.endpoint.secret_key(), &self.signer, &home, Timestamp::now().as_secs())?;
                    // OK=false and acknowledgement timeout are both failures, not 'connected'.
                    let ack = relay.send_event(&ev).ok_timeout(IO_TIMEOUT).await;
                    self.reports.send(Report::Health(index, ack.is_ok())).await?;
                }
                msg = notices.next() => match msg.context("public discovery socket closed")? {
                    RelayNotification::Event { subscription_id, event } if subscription_id == sub => {
                        let instant = Instant::now();
                        if instant >= reset_at {
                            reset_at = instant + Duration::from_secs(1);
                            budget = 16;
                        }
                        if budget > 0 {
                            budget -= 1;
                            if let Some(addr) = open_presence(&event, self.endpoint.id(), &self.homes, Timestamp::now().as_secs()) {
                                self.reports.send(Report::Peer(addr, event.created_at.as_secs())).await?;
                            }
                        }
                    }
                    RelayNotification::Message { message } => {
                        if matches!(*message, RelayMessage::Closed { subscription_id, .. } if *subscription_id == sub) {
                            bail!("public discovery subscription closed");
                        }
                    }
                    RelayNotification::RelayStatus { status } if !status.is_connected() => bail!("public discovery socket disconnected"),
                    _ => (),
                }
            }
        }
    }

    async fn follow(&self, index: usize, url: NostrUrl) {
        loop {
            let _ = self.connected(index, &url).await;
            if self
                .reports
                .send(Report::Health(index, false))
                .await
                .is_err()
            {
                break;
            }
            time::sleep(Duration::from_secs(30)).await;
        }
    }
}

/// Dropping the future, closing the endpoint, or dropping the receiver ends all subscriptions.
/// No task, signer or database is shared with the next lobby session.
pub(crate) async fn run(endpoint: Endpoint, updates: mpsc::Sender<Update>) {
    let urls = relay_urls();
    if urls.is_empty() {
        let _ = updates.send(Update::Available(false)).await;
        return;
    }
    let (reports, mut rx) = mpsc::channel(32);
    let session = Session {
        endpoint,
        signer: Keys::generate(),
        homes: iroh::defaults::prod::default_relay_map().urls(),
        reports,
    };
    let mut health = vec![None; urls.len()];
    let mut last_health = None;
    let mut seen = Seen::default();
    let workers = join_all(
        urls.into_iter()
            .enumerate()
            .map(|(i, url)| session.follow(i, url)),
    );
    tokio::pin!(workers);
    loop {
        let update = tokio::select! {
            _ = updates.closed() => break,
            _ = session.endpoint.closed() => break,
            _ = &mut workers => break,
            Some(report) = rx.recv() => match report {
                Report::Health(i, value) => {
                    health[i] = Some(value);
                    let available = health.contains(&Some(true));
                    if !available && health.contains(&None) || last_health == Some(available) {
                        continue;
                    }
                    last_health = Some(available);
                    Update::Available(available)
                }
                Report::Peer(addr, stamp) => {
                    if !seen.admit(addr.id, stamp, Timestamp::now().as_secs()) {
                        continue;
                    }
                    Update::Peer(addr)
                }
            },
        };
        if updates.send(update).await.is_err() {
            break;
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn independent_signatures_bind_author_timestamp_and_actual_route() {
        let homes: Vec<_> = iroh::defaults::prod::default_relay_map().urls();
        let key = SecretKey::generate();
        let me = SecretKey::generate().public();
        let signer = Keys::generate();
        let ev = announcement(&key, &signer, &homes[0], 1000).unwrap();
        assert!(ev.verify().is_ok());
        assert_eq!(
            open_presence(&ev, me, &homes, 1000),
            Some(EndpointAddr::new(key.public()).with_relay_url(homes[0].clone()))
        );
        assert!(open_presence(&ev, key.public(), &homes, 1000).is_none());
        assert!(open_presence(&ev, me, &homes, 1000 + TTL).is_none());
        assert!(open_presence(&ev, me, &homes, 989).is_none());

        let resign = |s: &Keys, content: String, stamp: u64, tag: &str| {
            EventBuilder::new(KIND, content)
                .tag(Tag::hashtag(tag))
                .custom_created_at(Timestamp::from_secs(stamp))
                .finalize(s)
                .unwrap()
        };
        for attack in [
            resign(&Keys::generate(), ev.content.clone(), 1000, TOPIC),
            resign(&signer, ev.content.clone(), 1001, TOPIC),
            resign(&signer, ev.content.clone(), 1000, "other"),
            resign(
                &signer,
                ev.content.replace(homes[0].as_str(), homes[1].as_str()),
                1000,
                TOPIC,
            ),
            resign(
                &signer,
                ev.content
                    .replace(&key.public().to_string(), &me.to_string()),
                1000,
                TOPIC,
            ),
        ] {
            assert!(attack.verify().is_ok());
            assert!(open_presence(&attack, me, &homes, 1000).is_none());
        }
        let mut forged = ev;
        forged.content.push(' ');
        assert!(forged.verify().is_err());
    }

    #[test]
    fn even_valid_endpoint_proofs_cannot_add_dial_targets_or_metadata() {
        let homes: Vec<_> = iroh::defaults::prod::default_relay_map().urls();
        let key = SecretKey::generate();
        let me = SecretKey::generate().public();
        let signer = Keys::generate();
        for dest in [
            "http://127.0.0.1/",
            "https://example.org/",
            "https://use1-1.relay.n0.iroh.link.:444/",
        ] {
            let ev = announcement(&key, &signer, &dest.parse().unwrap(), 1000).unwrap();
            assert!(open_presence(&ev, me, &homes, 1000).is_none());
        }
        let ev = announcement(&key, &signer, &homes[0], 1000).unwrap();
        let mut data: serde_json::Value = serde_json::from_str(&ev.content).unwrap();
        data["ip"] = "127.0.0.1".into();
        let ev = EventBuilder::new(KIND, data.to_string())
            .tag(Tag::hashtag(TOPIC))
            .custom_created_at(Timestamp::from_secs(1000))
            .finalize(&signer)
            .unwrap();
        assert!(open_presence(&ev, me, &homes, 1000).is_none());
    }

    #[test]
    fn peer_budget_rejects_replays_without_evicting_live_ids() {
        let mut seen = Seen::default();
        let peer = SecretKey::generate().public();
        assert!(seen.admit(peer, 1000, 1000));
        assert!(!seen.admit(peer, 1000, 1001));
        assert!(!seen.admit(peer, 999, 1001));
        for _ in 1..MAX_PEERS {
            assert!(seen.admit(SecretKey::generate().public(), 1000, 1000));
        }
        let extra = SecretKey::generate().public();
        assert!(!seen.admit(extra, 1001, 1001));
        assert!(seen.admit(peer, 1040, 1040));
        assert!(!seen.admit(peer, 1000, 1041));
        assert!(seen.admit(extra, 1090, 1090));
    }
}