gent-daemon 0.2.23

Local daemon, storage and synchronization for Gent chat clusters.
Documentation
use super::*;
use age::armor::ArmoredReader;
use age_core::format::read::age_stanza;
use base64::engine::general_purpose::STANDARD_NO_PAD;
use gent_protocol::secret_handoff::{FILENAME, MAX_ARMOR_BYTES, MAX_SECRET_BYTES, MEDIA_TYPE};
use std::io::Read;

// age v1 has a 16-byte stream nonce and a 16-byte authentication tag per
// chunk. A Gent handoff fits entirely in the first 64 KiB plaintext chunk.
const NONCE_BYTES: usize = 16;
const TAG_BYTES: usize = 16;

fn is_base64_32(value: &[u8]) -> bool {
    STANDARD_NO_PAD.decode_slice(value, &mut [0; 32]) == Ok(32)
}

// Walk the age recipient stanzas once, including unknown extensions (GREASE).
// Only the recipient's identity can authenticate the header MAC and payload.
fn envelope(binary: &[u8]) -> Option<()> {
    let mut rest = binary.strip_prefix(b"age-encryption.org/v1\n")?;
    let mut x25519 = false;
    while rest.starts_with(b"-> ") {
        let (next, stanza) = age_stanza(rest).ok()?;
        match stanza.tag {
            "scrypt" => return None,
            "X25519" => {
                let [share] = stanza.args.as_slice() else {
                    return None;
                };
                if !is_base64_32(share.as_bytes()) || stanza.body().len() != 32 {
                    return None;
                }
                x25519 = true;
            }
            _ => {}
        }
        rest = next;
    }
    let (mac, rest) = rest.strip_prefix(b"--- ")?.split_at_checked(43)?;
    let (_, payload) = rest.strip_prefix(b"\n")?.split_at_checked(NONCE_BYTES)?;
    let size = payload.len().checked_sub(TAG_BYTES)?;
    (x25519 && is_base64_32(mac) && (1..=MAX_SECRET_BYTES).contains(&size)).then_some(())
}

fn valid_armor(bytes: &[u8]) -> bool {
    if bytes.len() > MAX_ARMOR_BYTES
        || !bytes.is_ascii()
        || !bytes.starts_with(b"-----BEGIN AGE ENCRYPTED FILE-----")
    {
        return false;
    }
    let end = bytes
        .strip_suffix(b"\r\n")
        .or_else(|| bytes.strip_suffix(b"\n"))
        .unwrap_or(bytes);
    if !end.ends_with(b"-----END AGE ENCRYPTED FILE-----") {
        return false;
    }
    let mut binary = Vec::new();
    ArmoredReader::new(bytes).read_to_end(&mut binary).is_ok() && envelope(&binary).is_some()
}

pub(super) fn file_part(armor: &str) -> Result<FilePart> {
    ensure!(valid_armor(armor.as_bytes()), "invalid armored age handoff");
    Ok(FilePart {
        name: FILENAME.into(),
        media_type: MEDIA_TYPE.into(),
        data_base64: STANDARD.encode(armor),
    })
}

impl StoreSession<'_> {
    pub(super) fn secret_read(&self, who: &Agent, id: &str) -> Result<Value> {
        let message = self.message(id)?;
        ensure!(
            message.recipient == who.id
                && self.deliverable(&message)?
                && self.relay_inbox_visible(&message)?,
            UNAVAILABLE
        );
        let [file] = message.files.as_slice() else {
            anyhow::bail!(UNAVAILABLE)
        };
        ensure!(
            message.text.is_empty()
                && message.attachments.is_empty()
                && file.name == FILENAME
                && file.media_type == MEDIA_TYPE
                && file.data_base64.len() <= MAX_ARMOR_BYTES.div_ceil(3) * 4,
            UNAVAILABLE
        );
        let bytes = STANDARD
            .decode(&file.data_base64)
            .ok()
            .context(UNAVAILABLE)?;
        ensure!(valid_armor(&bytes), UNAVAILABLE);
        let armor = std::str::from_utf8(&bytes).ok().context(UNAVAILABLE)?;
        Ok(json!({"message_id":message.id,"sender":message.sender,"format":"age-v1","armor":armor}))
    }
}

#[cfg(test)]
mod tests;