engawa-chat 0.4.0

A peer-to-peer chat lobby for editors and browsers
//! Shared room identities, signed records, and gossip payloads.

use anyhow::{Result, ensure};
use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey};
use serde::{Deserialize, Serialize};

pub(crate) const WEEK: i64 = 7 * 24 * 60 * 60 * 1000;
pub(crate) const SKEW: i64 = 60_000;
pub(crate) const POSTS: usize = 200;
pub(crate) const FRAME: usize = 3600;
pub(crate) const PAGE: usize = 20;
pub(crate) const ROOM_TRAILER: usize = 16;
pub(crate) const MAX_ROOM_FRAME: usize = 4096;
pub(crate) const PRESENCE: i64 = 90_000;
pub(crate) const ROOMS: usize = 512;
pub(crate) const DEFAULTS: [(&str, &str, bool); 3] = [
    ("雑談", "lounge", true),
    ("もくもく", "focus", false),
    ("質問", "questions", true),
];

pub(crate) fn public_relay(url: &url::Url) -> bool {
    let Some(domain) = url.domain() else {
        return false;
    };
    let host = domain.strip_suffix('.').unwrap_or(domain);
    url.scheme() == "https"
        && url.username().is_empty()
        && url.password().is_none()
        && url.port() != Some(0)
        && url.query().is_none()
        && url.fragment().is_none()
        && url.path() == "/"
        && host.len() <= 253
        && host.contains('.')
        && host.split('.').all(|label| {
            !label.is_empty()
                && label.len() <= 63
                && !label.starts_with('-')
                && !label.ends_with('-')
                && label
                    .bytes()
                    .all(|c| c.is_ascii_alphanumeric() || c == b'-')
        })
        && !matches!(
            host.rsplit('.').next(),
            Some(
                "localhost"
                    | "local"
                    | "localdomain"
                    | "internal"
                    | "test"
                    | "invalid"
                    | "example"
                    | "onion"
                    | "arpa"
                    | "home"
                    | "lan"
                    | "corp"
                    | "alt"
            )
        )
}

pub(crate) fn digest(domain: &'static str, fields: &[&[u8]]) -> blake3::Hash {
    let mut h = blake3::Hasher::new_derive_key(domain);
    for field in fields {
        h.update(&(field.len() as u64).to_be_bytes());
        h.update(field);
    }
    h.finalize()
}

pub(crate) fn is_hex(s: &str, len: usize) -> bool {
    s.len() == len
        && s.bytes()
            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct Room {
    pub id: String,
    pub name: String,
    pub history: bool,
}

impl Room {
    pub(crate) fn identity(name: &str, history: bool) -> Result<blake3::Hash> {
        ensure!(
            !name.is_empty()
                && name.len() <= 96
                && name.trim() == name
                && !name.starts_with('#')
                && !name.chars().any(char::is_control),
            "部屋名は空白だけにせず、96バイト以内で入力してください"
        );
        let builtin = DEFAULTS
            .iter()
            .find(|(n, _, h)| *n == name && *h == history);
        let (kind, key) = builtin.map_or(("custom", name), |(_, slug, _)| ("builtin", *slug));
        Ok(digest(
            "engawa/v1/room",
            &[kind.as_bytes(), key.as_bytes(), &[u8::from(history)]],
        ))
    }

    pub(crate) fn new(name: &str, history: bool) -> Result<Self> {
        Ok(Self {
            id: Self::identity(name, history)?.to_hex().to_string(),
            name: name.into(),
            history,
        })
    }

    pub(crate) fn consistent(&self) -> bool {
        Self::identity(&self.name, self.history).is_ok_and(|hash| hash.to_hex().as_str() == self.id)
    }
}

#[derive(Clone, Deserialize, Serialize)]
#[serde(rename_all = "snake_case", deny_unknown_fields)]
pub(crate) enum Body {
    Message { nonce: String, text: String },
    Withdrawal { signature: String },
}

#[derive(Clone, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct Record {
    pub author: String,
    pub stamp: i64,
    // The original post signature identifies it even when its nonce and text are erased.
    pub reference: String,
    pub body: Body,
}

fn valid_text(text: &str) -> bool {
    !text.trim().is_empty()
        && text.len() <= 1024
        && !text
            .chars()
            .any(|c| c.is_control() && c != '\n' && c != '\t')
}

impl Record {
    fn post_digest(room: &str, stamp: i64, nonce: &str, text: &str) -> blake3::Hash {
        digest(
            "engawa/v1/post",
            &[
                room.as_bytes(),
                &stamp.to_be_bytes(),
                nonce.as_bytes(),
                text.as_bytes(),
            ],
        )
    }

    pub(crate) fn new(key: &SigningKey, room: &str, stamp: i64, text: &str) -> Result<Self> {
        ensure!(
            valid_text(text),
            "本文は空白だけにせず、1024バイト以内で入力してください"
        );
        let mut nonce = [0u8; 16];
        getrandom::fill(&mut nonce)?;
        let nonce = hex::encode(nonce);
        let message = Self::post_digest(room, stamp, &nonce, text);
        Ok(Self {
            author: hex::encode(key.verifying_key().to_bytes()),
            stamp,
            reference: hex::encode(key.sign(message.as_bytes()).to_bytes()),
            body: Body::Message {
                nonce,
                text: text.into(),
            },
        })
    }

    pub(crate) fn id(&self, room: &str) -> String {
        digest(
            "engawa/v1/post-id",
            &[
                room.as_bytes(),
                self.author.as_bytes(),
                &self.stamp.to_be_bytes(),
                self.reference.as_bytes(),
            ],
        )
        .to_hex()
        .to_string()
    }

    pub(crate) fn erase(&mut self, key: &SigningKey, room: &str) -> Result<()> {
        ensure!(
            self.author == hex::encode(key.verifying_key().to_bytes()) && !self.dead(),
            "このセッションの発言だけ取り消せます"
        );
        let proof = digest("engawa/v1/withdraw", &[self.id(room).as_bytes()]);
        self.body = Body::Withdrawal {
            signature: hex::encode(key.sign(proof.as_bytes()).to_bytes()),
        };
        Ok(())
    }

    pub(crate) fn dead(&self) -> bool {
        matches!(self.body, Body::Withdrawal { .. })
    }

    pub(crate) fn verified(&self, room: &str, oldest: i64, time: i64) -> bool {
        if self.stamp <= oldest
            || self.stamp > time + SKEW
            || !is_hex(&self.author, 64)
            || !is_hex(&self.reference, 128)
        {
            return false;
        }
        let mut author = [0; 32];
        if hex::decode_to_slice(&self.author, &mut author).is_err() {
            return false;
        }
        let Ok(key) = VerifyingKey::from_bytes(&author) else {
            return false;
        };
        let (sig, data) = match &self.body {
            Body::Message { nonce, text } if valid_text(text) && is_hex(nonce, 32) => (
                &self.reference,
                Self::post_digest(room, self.stamp, nonce, text),
            ),
            Body::Withdrawal { signature } if is_hex(signature, 128) => (
                signature,
                digest("engawa/v1/withdraw", &[self.id(room).as_bytes()]),
            ),
            _ => return false,
        };
        let mut signature = [0; 64];
        hex::decode_to_slice(sig, &mut signature).is_ok()
            && key
                .verify_strict(data.as_bytes(), &Signature::from_bytes(&signature))
                .is_ok()
    }
}

#[derive(Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum Packet {
    Item(Record),
    Hello,
    Offer(Vec<(String, bool)>),
    Need(Vec<(String, bool)>),
}

impl Packet {
    pub(crate) fn encode(&self) -> Result<Vec<u8>> {
        let bytes = serde_json::to_vec(self)?;
        ensure!(bytes.len() <= FRAME, "パケットが大きすぎます");
        Ok(bytes)
    }
}