engawa-chat 0.2.1

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
415
416
417
418
419
420
421
422
423
424
425
//! Mainline bootstraps the public lobby only. Room payloads never enter the DHT.
//! With `ENGAWA_PEER` set, use loopback QUIC instead: an empty value starts a seed;
//! `<endpoint-id>@127.0.0.1:<port>` connects to a seed's `local peer ...` status.

use std::{
    collections::{HashMap, VecDeque},
    env,
    future::pending,
    net::{Ipv4Addr, SocketAddrV4},
    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
};

use anyhow::{Context, Result, anyhow, ensure};
use distributed_topic_tracker::{AutoDiscoveryGossip, RecordPublisher, TopicId as TrackerId};
use ed25519_dalek::SigningKey;
use futures_lite::StreamExt;
use iroh::{
    Endpoint, EndpointAddr, EndpointId, RelayMode, RelayUrl, SecretKey, Signature, Watcher,
    address_lookup::memory::MemoryLookup,
    endpoint::{NetReportConfig, PortmapperConfig, presets},
    protocol::Router,
};
use iroh_gossip::{
    Event as GossipEvent, Gossip, GossipReceiver, GossipSender, JoinOptions, TopicId,
};
use serde::Deserialize;
use tokio::{sync::mpsc, task::JoinSet, time};

use crate::protocol::{MAX_ROOM_FRAME, ROOM_TRAILER, public_relay};

const LOBBY: &str = "engawa/public-lobby/v1";
const NOTICE_TAG: &[u8] = b"engawa/notice/v1\0";
const MAX_NOTICE: usize = 1024;
const REFRESH: Duration = Duration::from_secs(20);
const HINT_TTL: Duration = Duration::from_secs(120);
const MAX_HINT_ROOMS: usize = 256;
const MAX_ROOM_PEERS: usize = 8;

#[derive(Debug)]
pub enum Cmd {
    Join(String),
    Leave,
    Send(Vec<u8>),
    Announce(Vec<u8>),
}

#[derive(Debug)]
pub enum Event {
    Lobby(Vec<u8>),
    Room(String, Vec<u8>),
    Subscribed(String),
    InviteEndpoint(Option<(String, String)>),
    Ready(String),
    Status(String),
}

struct Room {
    id: String,
    topic: TopicId,
    tx: GossipSender,
    rx: GossipReceiver,
    notice: Option<Vec<u8>>,
}

#[derive(Default)]
struct Hints(HashMap<TopicId, VecDeque<(EndpointId, Instant)>>);

impl Hints {
    fn remember(&mut self, topic: TopicId, peer: EndpointId, now: Instant) {
        if self.0.len() >= MAX_HINT_ROOMS && !self.0.contains_key(&topic) {
            // Do not let unknown rooms displace live rooms on every packet.
            return;
        }
        let peers = self.0.entry(topic).or_default();
        peers.retain(|(id, _)| *id != peer);
        if peers.len() == MAX_ROOM_PEERS {
            peers.pop_front();
        }
        peers.push_back((peer, now));
    }

    fn peers(&self, topic: TopicId) -> impl Iterator<Item = EndpointId> + '_ {
        self.0.get(&topic).into_iter().flatten().map(|p| p.0)
    }

    fn expire(&mut self, now: Instant) {
        self.0.retain(|_, peers| {
            while peers
                .front()
                .is_some_and(|p| now.duration_since(p.1) >= HINT_TTL)
            {
                peers.pop_front();
            }
            !peers.is_empty()
        });
    }
}

fn room_topic(id: &str) -> Option<TopicId> {
    if id.len() != 64 || id.bytes().any(|b| b.is_ascii_uppercase()) {
        return None;
    }
    id.parse().ok()
}

fn notice_topic(payload: &[u8]) -> Option<TopicId> {
    #[derive(Deserialize)]
    struct Notice<'a> {
        id: &'a str,
    }
    if payload.len() > MAX_NOTICE {
        return None;
    }
    room_topic(serde_json::from_slice::<Notice<'_>>(payload).ok()?.id)
}

fn unix_seconds() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs()
}

// Signature covers the protocol tag, timestamp, sequence and original metadata. Gossip's
// delivered_from identifies the last hop, not the endpoint that can bootstrap the room.
fn signed_notice(key: &SecretKey, seconds: u64, sequence: u64, notice: &[u8]) -> Vec<u8> {
    let mut wire =
        Vec::with_capacity(NOTICE_TAG.len() + 16 + notice.len() + 32 + Signature::LENGTH);
    wire.extend_from_slice(NOTICE_TAG);
    wire.extend_from_slice(&seconds.to_be_bytes());
    wire.extend_from_slice(&sequence.to_be_bytes());
    wire.extend_from_slice(notice);
    let sig = key.sign(&wire);
    wire.extend_from_slice(key.public().as_bytes());
    wire.extend_from_slice(&sig.to_bytes());
    wire
}

fn open_notice(wire: &[u8], now: u64) -> Option<(EndpointId, TopicId, &[u8])> {
    let (wire, sig) = wire.split_last_chunk::<{ Signature::LENGTH }>()?;
    let (signed, key) = wire.split_last_chunk::<32>()?;
    let (stamp, rest) = signed.strip_prefix(NOTICE_TAG)?.split_first_chunk::<8>()?;
    let (_, payload) = rest.split_first_chunk::<8>()?;
    if now.abs_diff(u64::from_be_bytes(*stamp)) > HINT_TTL.as_secs() {
        return None;
    }
    let topic = notice_topic(payload)?;
    let peer = EndpointId::from_bytes(key).ok()?;
    peer.verify(signed, &Signature::from_bytes(sig)).ok()?;
    Some((peer, topic, payload))
}

async fn announce(
    tx: &GossipSender,
    room: Option<&Room>,
    key: &SecretKey,
    seq: &mut u64,
) -> Result<()> {
    if let Some(notice) = room.and_then(|r| r.notice.as_deref()) {
        *seq += 1;
        tx.broadcast(signed_notice(key, unix_seconds(), *seq, notice).into())
            .await?;
    }
    Ok(())
}

fn explicit_peer(value: &str) -> Result<Option<EndpointAddr>> {
    if value.is_empty() {
        return Ok(None);
    }
    let (id, addr) = value
        .split_once('@')
        .context("expected ENGAWA_PEER=<id>@127.0.0.1:<port>")?;
    let id = id.parse().context("invalid ENGAWA_PEER endpoint id")?;
    let addr: SocketAddrV4 = addr.parse().context("invalid ENGAWA_PEER socket address")?;
    ensure!(
        addr.ip().is_loopback() && addr.port() != 0,
        "ENGAWA_PEER requires an IPv4 loopback address and a nonzero port"
    );
    Ok(Some(EndpointAddr::new(id).with_ip_addr(addr.into())))
}

fn explicit_relay(value: &str) -> Result<RelayUrl> {
    let relay: RelayUrl = value.parse().context("invalid ENGAWA_INVITE_RELAY URL")?;
    ensure!(
        public_relay(&relay),
        "ENGAWA_INVITE_RELAY requires a public HTTPS relay origin"
    );
    Ok(relay)
}

async fn emit(tx: &mpsc::Sender<Event>, event: Event) -> Result<()> {
    tx.send(event)
        .await
        .map_err(|_| anyhow!("local event receiver closed"))
}

pub async fn run(mut cmd: mpsc::Receiver<Cmd>, events: mpsc::Sender<Event>) -> Result<()> {
    let local = env::var_os("ENGAWA_PEER");
    let relay = env::var_os("ENGAWA_INVITE_RELAY");
    ensure!(
        local.is_none() || relay.is_none(),
        "choose ENGAWA_PEER or ENGAWA_INVITE_RELAY, not both"
    );
    let discover = local.is_none() && relay.is_none();
    let (endpoint, seed) = if let Some(value) = &local {
        let peer = explicit_peer(value.to_str().context("ENGAWA_PEER must be UTF-8")?)?;
        let seed = peer.as_ref().map(|p| p.id);
        let endpoint = Endpoint::builder(presets::Minimal)
            .clear_ip_transports()
            .bind_addr(SocketAddrV4::new(Ipv4Addr::LOCALHOST, 0))?
            .address_lookup(MemoryLookup::from_endpoint_info(peer))
            .portmapper_config(PortmapperConfig::Disabled)
            .net_report_config(NetReportConfig::minimal())
            .bind()
            .await?;
        (endpoint, seed)
    } else if let Some(value) = &relay {
        let relay = explicit_relay(
            value
                .to_str()
                .context("ENGAWA_INVITE_RELAY must be UTF-8")?,
        )?;
        let endpoint = Endpoint::builder(presets::Minimal)
            .relay_mode(RelayMode::custom([relay]))
            .clear_ip_transports()
            .portmapper_config(PortmapperConfig::Disabled)
            .bind()
            .await?;
        (endpoint, None)
    } else {
        (Endpoint::bind(presets::N0).await?, None)
    };
    let key = endpoint.secret_key();
    let me = endpoint.id();
    let gossip = Gossip::builder()
        .max_message_size(MAX_ROOM_FRAME + 128)
        .spawn(endpoint.clone());
    let router = Router::builder(endpoint.clone())
        .accept(iroh_gossip::ALPN, gossip.clone())
        .spawn();
    let tracker_topic = TrackerId::from(LOBBY);
    let lobby_id = TopicId::from_bytes(tracker_topic.hash());
    let (lobby_tx, mut lobby_rx) = gossip
        .subscribe_with_opts(
            lobby_id,
            JoinOptions::with_bootstrap(seed).with_subscription_capacity(128),
        )
        .await?
        .split();

    // DHT startup can take a long time. A relay invitation does not need the public lobby.
    let mut discovery = JoinSet::new();
    let mut tracker = None;
    if discover {
        let publisher = RecordPublisher::builder(
            tracker_topic,
            SigningKey::from_bytes(&key.to_bytes()),
            LOBBY.as_bytes(),
        )
        .build();
        let gossip = gossip.clone();
        discovery.spawn(async move {
            gossip
                .subscribe_and_join_with_auto_discovery_no_wait(publisher)
                .await
        });
    }
    let mut relay_status = endpoint.home_relay_status().stream();
    let status = if local.is_some() {
        let addr = endpoint
            .bound_sockets()
            .into_iter()
            .find(|a| a.ip().is_loopback())
            .context("missing loopback socket")?;
        format!("local peer {me}@{addr}")
    } else if !discover {
        "招待用リレーに接続中".into()
    } else {
        "公開ロビーのピアを探索中".into()
    };
    emit(&events, Event::Status(status)).await?;
    let mut room: Option<Room> = None;
    let mut hints = Hints::default();
    let mut seq = 0u64;
    let mut refresh = time::interval_at(time::Instant::now() + REFRESH, REFRESH);
    refresh.set_missed_tick_behavior(time::MissedTickBehavior::Skip);
    loop {
        tokio::select! {
            Some(result) = discovery.join_next(), if !discovery.is_empty() => {
                match result.context("public lobby discovery task stopped").and_then(|r| r) {
                    Ok(topic) => tracker = Some(topic),
                    Err(e) => {
                        eprintln!("engawa: public lobby unavailable: {e:#}");
                        emit(&events, Event::Status("公開ロビーに接続できません(招待で参加できます)".into())).await?;
                    }
                }
            },
            change = relay_status.next(), if local.is_none() => {
                let statuses = change.context("relay status stream closed")?;
                let addr = statuses.iter()
                    .find(|r| r.is_connected() && public_relay(r.url()))
                    .map(|r| (me.to_string(), r.url().to_string()));
                if let Some(err) = statuses.iter().find_map(|r| r.last_error()) && addr.is_none() {
                    let status = format!("招待用リレーに接続できません: {err:#}");
                    eprintln!("engawa: {status}");
                    emit(&events, Event::Status(status)).await?;
                } else if !discover {
                    let status = if addr.is_some() { "招待用リレーに接続" } else { "招待用リレーに接続中" };
                    emit(&events, Event::Status(status.into())).await?;
                }
                emit(&events, Event::InviteEndpoint(addr)).await?;
            },
            command = cmd.recv() => match command {
                None => break,
                Some(Cmd::Leave) => room = None,
                Some(Cmd::Join(id)) => {
                    let topic = room_topic(&id).context("invalid room id")?;
                    ensure!(topic != lobby_id, "room id collides with the lobby");
                    if room.as_ref().is_some_and(|r| r.topic == topic) { continue; }
                    let opts = JoinOptions::with_bootstrap(hints.peers(topic)).with_subscription_capacity(256);
                    let (tx, rx) = gossip.subscribe_with_opts(topic, opts).await?.split();
                    emit(&events, Event::Subscribed(id.clone())).await?;
                    room = Some(Room { topic, id, tx, rx, notice: None });
                }
                Some(Cmd::Announce(notice)) => {
                    if let Some(r) = &mut room && notice_topic(&notice) == Some(r.topic) {
                        r.notice = Some(notice);
                        announce(&lobby_tx, Some(r), key, &mut seq).await?;
                    }
                }
                Some(Cmd::Send(mut payload)) => {
                    if let Some(r) = &room && !payload.is_empty() && payload.len() <= MAX_ROOM_FRAME {
                        // Identical requests/responses must still pass gossip's content-hash dedup.
                        seq += 1;
                        payload.reserve(ROOM_TRAILER);
                        payload.extend_from_slice(&me.as_bytes()[..8]);
                        payload.extend_from_slice(&seq.to_be_bytes());
                        r.tx.broadcast(payload.into()).await?;
                    }
                }
            },
            event = lobby_rx.next() => match event.context("lobby subscription closed")?? {
                GossipEvent::Received(msg) => {
                    if let Some((peer, topic, notice)) = open_notice(&msg.content, unix_seconds())
                        && peer != me && topic != lobby_id {
                        hints.remember(topic, peer, Instant::now());
                        if let Some(r) = &room && r.topic == topic && !r.rx.is_joined() {
                            r.tx.join_peers(vec![peer]).await?;
                        }
                        emit(&events, Event::Lobby(notice.to_vec())).await?;
                    }
                }
                GossipEvent::NeighborUp(_) => {
                    announce(&lobby_tx, room.as_ref(), key, &mut seq).await?;
                    if discover { emit(&events, Event::Status("公開ロビーに接続".into())).await?; }
                }
                GossipEvent::NeighborDown(_) if discover && !lobby_rx.is_joined() => {
                    emit(&events, Event::Status("公開ロビーのピアを探索中".into())).await?;
                }
                _ => {}
            },
            event = async { match &mut room { Some(r) => r.rx.next().await, None => pending().await } } => {
                let r = room.as_ref().expect("room event requires subscription");
                match event.context("room subscription closed")?? {
                    GossipEvent::Received(msg) if msg.content.len() > ROOM_TRAILER && msg.content.len() <= MAX_ROOM_FRAME + ROOM_TRAILER => {
                        emit(&events, Event::Room(r.id.clone(), msg.content[..msg.content.len()-ROOM_TRAILER].to_vec())).await?;
                    }
                    GossipEvent::NeighborUp(_) | GossipEvent::Lagged => {
                        emit(&events, Event::Ready(r.id.clone())).await?;
                    }
                    _ => {}
                }
            },
            _ = refresh.tick() => {
                hints.expire(Instant::now());
                if !lobby_rx.is_joined() && let Some(seed) = seed {
                    lobby_tx.join_peers(vec![seed]).await?;
                }
                announce(&lobby_tx, room.as_ref(), key, &mut seq).await?;
            }
            _ = events.closed() => break,
        }
    }
    drop((room, lobby_tx, lobby_rx, tracker));
    router.shutdown().await?;
    Ok(())
}

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

    #[test]
    fn notices_verify_origin_metadata_and_freshness() {
        let key = SecretKey::generate();
        let notice = format!(
            r#"{{"id":"{}","name":"部屋","history":false}}"#,
            "cd".repeat(32)
        );
        let mut wire = signed_notice(&key, 1000, 7, notice.as_bytes());
        let (peer, topic, payload) = open_notice(&wire, 1001).unwrap();
        assert_eq!(peer, key.public());
        assert_eq!(Some(topic), notice_topic(notice.as_bytes()));
        assert_eq!(payload, notice.as_bytes());
        assert!(open_notice(&wire, 2000).is_none());
        wire[NOTICE_TAG.len() + 15] ^= 1;
        assert!(open_notice(&wire, 1000).is_none());
    }

    #[test]
    fn local_bootstrap_rejects_external_addresses() {
        let id = SecretKey::generate().public();
        assert!(explicit_peer("").unwrap().is_none());
        assert!(explicit_peer(&format!("{id}@192.0.2.1:1")).is_err());
        assert!(explicit_peer(&format!("{id}@127.0.0.1:0")).is_err());
        assert_eq!(
            explicit_peer(&format!("{id}@127.0.0.1:1"))
                .unwrap()
                .unwrap()
                .id,
            id
        );
    }
}