engawa-chat 0.4.0

A peer-to-peer chat lobby for editors and browsers
//! Signed directory notices shared by native and browser peers.

use std::time::Duration;

use anyhow::{Result as WireResult, ensure};
#[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
use futures_lite::stream::Boxed as LookupStream;
#[cfg(all(target_family = "wasm", target_os = "unknown"))]
use futures_lite::stream::BoxedLocal as LookupStream;
use iroh::{
    EndpointAddr, EndpointId, RelayUrl, SecretKey, Signature,
    address_lookup::{self, AddressLookup},
};
use iroh_gossip::TopicId;

use crate::protocol::{Room, is_hex};
use crate::scope::Scope;

const NOTICE_TAG: &[u8] = b"engawa/notice/v1\0";
// 0.2.1 accepts at most 512 bytes of room JSON in its directory.
const MAX_NOTICE: usize = 512;
const MAX_SIGNED_NOTICE: usize = NOTICE_TAG.len() + 16 + MAX_NOTICE + 32 + Signature::LENGTH;
pub(crate) const REFRESH: Duration = Duration::from_secs(20);
pub(crate) const HINT_TTL: Duration = Duration::from_secs(120);
pub(crate) const MAX_HINT_ROOMS: usize = 256;
pub(crate) const MAX_ROOM_PEERS: usize = 8;

// An explicit-relay host (including 0.2.1) does not publish endpoint records. Its invitees
// use that same relay. Try this route without retaining a lookup entry for every public ID.
#[derive(Debug)]
pub(crate) struct InviteRelay(pub(crate) RelayUrl);

impl AddressLookup for InviteRelay {
    fn resolve(
        &self,
        peer: EndpointId,
    ) -> Option<LookupStream<Result<address_lookup::Item, address_lookup::Error>>> {
        let addr = EndpointAddr::new(peer).with_relay_url(self.0.clone());
        let item = address_lookup::Item::new(addr.into(), "engawa-invite-relay", None);
        Some(Box::pin(futures_lite::stream::once(Ok(item))))
    }
}

pub(crate) fn lobby_topic() -> TopicId {
    // distributed-topic-tracker's TopicId::from("engawa/public-lobby/v1"): SHA-512[..32].
    // The native compatibility test checks this value against the actual tracker implementation.
    TopicId::from_bytes([
        0x07, 0xdb, 0xbb, 0xdd, 0x0c, 0xe1, 0x0e, 0xe8, 0x2a, 0xe5, 0xba, 0x90, 0x96, 0x8e, 0x2c,
        0x80, 0x0b, 0x87, 0xcf, 0x1f, 0x9f, 0xdb, 0x0e, 0x86, 0x5d, 0x8a, 0x63, 0xcd, 0xbd, 0x58,
        0x3e, 0x3d,
    ])
}

pub(crate) fn room_topic(id: &str) -> Option<TopicId> {
    if !is_hex(id, 64) {
        return None;
    }
    id.parse().ok().filter(|topic| *topic != lobby_topic())
}

pub(crate) fn signed_notice(
    scope: &Scope,
    key: &SecretKey,
    seconds: u64,
    sequence: u64,
    room: &Room,
) -> WireResult<Vec<u8>> {
    ensure!(scope.accepts(room), "部屋はこの縁側に属していません");
    scope.seal_notice(notice_bytes(key, seconds, sequence, room))
}

fn notice_bytes(key: &SecretKey, seconds: u64, sequence: u64, room: &Room) -> Vec<u8> {
    // String escaping can double quotes/backslashes. Room names cannot contain control characters.
    let max_json =
        br#"{"id":"","name":"","history":false}"#.len() + room.id.len() + 2 * room.name.len();
    let mut wire = Vec::with_capacity(NOTICE_TAG.len() + 16 + max_json + 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());
    serde_json::to_writer(&mut wire, room).expect("room metadata serializes to a byte vector");
    let signature = key.sign(&wire);
    wire.extend_from_slice(key.public().as_bytes());
    wire.extend_from_slice(&signature.to_bytes());
    wire
}

// Gossip's delivered_from is only the last hop. Authenticate the origin, original timestamp
// and history policy before either storing a dial hint or showing a directory entry.
pub(crate) fn open_notice(
    scope: &Scope,
    wire: &[u8],
    now: u64,
) -> Option<(EndpointId, TopicId, Room, u64)> {
    let wire = scope.open_notice(wire, MAX_SIGNED_NOTICE)?;
    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>()?;
    let stamp = u64::from_be_bytes(*stamp);
    if payload.len() > MAX_NOTICE || now.abs_diff(stamp) > HINT_TTL.as_secs() {
        return None;
    }
    let peer = EndpointId::from_bytes(key).ok()?;
    peer.verify(signed, &Signature::from_bytes(sig)).ok()?;
    let room: Room = serde_json::from_slice(payload).ok()?;
    if !scope.accepts(&room) {
        return None;
    }
    let topic = room_topic(&room.id)?;
    if topic == scope.lobby_topic() {
        return None;
    }
    Some((peer, topic, room, stamp))
}

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

    #[test]
    fn encoder_matches_the_0_2_1_wire_format() {
        let key = SecretKey::generate();
        let room = Room::new("本棚", true).unwrap();
        let json = format!(r#"{{"id":"{}","name":"本棚","history":true}}"#, room.id);
        let mut legacy = b"engawa/notice/v1\0".to_vec();
        legacy.extend_from_slice(&1000u64.to_be_bytes());
        legacy.extend_from_slice(&7u64.to_be_bytes());
        legacy.extend_from_slice(json.as_bytes());
        let signature = key.sign(&legacy);
        legacy.extend_from_slice(key.public().as_bytes());
        legacy.extend_from_slice(&signature.to_bytes());
        assert_eq!(
            signed_notice(&Scope::Public, &key, 1000, 7, &room).unwrap(),
            legacy
        );
        assert_eq!(
            open_notice(&Scope::Public, &legacy, 1000).unwrap().2.id,
            room.id
        );
    }

    #[test]
    fn explicit_relay_can_route_a_third_peer_without_a_direct_address() {
        use futures_lite::{StreamExt, future::block_on};

        let relay: RelayUrl = "https://relay.example.org/".parse().unwrap();
        let origin = SecretKey::generate().public();
        let mut routes = InviteRelay(relay.clone()).resolve(origin).unwrap();
        let route = block_on(routes.next())
            .unwrap()
            .unwrap()
            .into_endpoint_addr();
        assert_eq!(route, EndpointAddr::new(origin).with_relay_url(relay));
    }

    #[test]
    fn v1_notices_bind_origin_room_policy_and_original_time() {
        let key = SecretKey::generate();
        let mut room = Room::new("本棚", false).unwrap();
        let scope = Scope::Public;
        let mut wire = signed_notice(&scope, &key, 1000, 7, &room).unwrap();
        let (origin, topic, actual, stamp) = open_notice(&scope, &wire, 1100).unwrap();
        assert_eq!(origin, key.public());
        assert_eq!(Some(topic), room_topic(&room.id));
        assert_eq!(actual.id, room.id);
        assert_eq!(stamp, 1000);
        assert!(open_notice(&scope, &wire, 1121).is_none());
        assert!(open_notice(&scope, &wire, 879).is_none());
        wire[NOTICE_TAG.len() + 15] ^= 1;
        assert!(open_notice(&scope, &wire, 1000).is_none());
        wire[NOTICE_TAG.len() + 15] ^= 1;
        let start = wire.len() - 32 - Signature::LENGTH;
        wire[start..start + 32].copy_from_slice(SecretKey::generate().public().as_bytes());
        assert!(open_notice(&scope, &wire, 1000).is_none());
        room.history = true;
        assert!(open_notice(&scope, &notice_bytes(&key, 1000, 8, &room), 1000).is_none());
        room.name = "x".repeat(MAX_NOTICE);
        assert!(open_notice(&scope, &notice_bytes(&key, 1000, 9, &room), 1000).is_none());
    }

    #[test]
    fn private_directory_rejects_wrong_scope_plaintext_tampering_and_stale_notices() {
        let a = Scope::from_key_hex(&"01".repeat(32)).unwrap();
        let b = Scope::from_key_hex(&"02".repeat(32)).unwrap();
        let key = SecretKey::generate();
        let room = a.room("秘密の書斎", true).unwrap();
        let mut wire = signed_notice(&a, &key, 1000, 7, &room).unwrap();
        let (peer, topic, actual, stamp) = open_notice(&a, &wire, 1100).unwrap();
        assert_eq!(
            (peer, actual.id, stamp),
            (key.public(), room.id.clone(), 1000)
        );
        assert!(
            !wire
                .windows(room.name.len())
                .any(|s| s == room.name.as_bytes())
        );
        assert!(!wire.windows(room.id.len()).any(|s| s == room.id.as_bytes()));
        assert_ne!(wire, signed_notice(&a, &key, 1000, 7, &room).unwrap());
        assert!(open_notice(&Scope::Public, &wire, 1000).is_none());
        assert!(open_notice(&b, &wire, 1000).is_none());
        assert!(open_notice(&a, &wire, 1121).is_none());
        assert!(a.open_room(topic, &wire).is_none());
        wire[0] ^= 1;
        assert!(open_notice(&a, &wire, 1000).is_none());

        let raw = notice_bytes(&key, 1000, 7, &room);
        assert!(open_notice(&a, &raw, 1000).is_none());
        assert!(signed_notice(&Scope::Public, &key, 1000, 7, &room).is_err());
        assert!(open_notice(&Scope::Public, &raw, 1000).is_none());
        // Even an authorized sender cannot cause a foreign room to be joined.
        let wrong_room = a
            .seal_notice(notice_bytes(
                &key,
                1000,
                7,
                &b.room("秘密の書斎", true).unwrap(),
            ))
            .unwrap();
        assert!(open_notice(&a, &wrong_room, 1000).is_none());
    }
}