mailcycle 0.7.0

Rust email API client: create addresses that receive email, read and decrypt messages on your machine, send email, verify webhooks and stream events.
Documentation
//! Opening a stored message.
//!
//! Two seals reach a client. Mail from outside, and copies of what was sent,
//! are sealed by the mail server to the address's public key; mail the
//! account's own devices delivered is sealed under the address's symmetric
//! key. Either opens here, with keys derived from the phrase.
//!
//! Without the keys, or with the wrong ones, a message comes back with
//! `opened: false` and empty content rather than an error, so one unreadable
//! message does not hide the rest of a page.

use serde_json::Value;

use crate::crypto::asymmetric::{open_attachment_with_key, open_with_private_key, AsymmetricBox};
use crate::crypto::cipher::{open_json, SealedBox};
use crate::error::Result;
use crate::keys::Keys;
use crate::models::{Attachment, Message};
use crate::trackers::strip_remote_content;

fn text(value: Option<&Value>) -> String {
    value.and_then(Value::as_str).unwrap_or_default().to_string()
}

fn address_of(value: Option<&Value>) -> String {
    match value {
        Some(Value::String(s)) => s.clone(),
        Some(Value::Object(_)) => text(value.and_then(|v| v.get("address"))),
        _ => String::new(),
    }
}

fn name_of(value: Option<&Value>) -> String {
    match value {
        Some(Value::Object(_)) => text(value.and_then(|v| v.get("name"))),
        _ => String::new(),
    }
}

fn attachments_of(value: Option<&Value>) -> Vec<Attachment> {
    let Some(Value::Array(items)) = value else { return Vec::new() };
    items
        .iter()
        .enumerate()
        .map(|(index, item)| {
            let size = item
                .get("size")
                .and_then(Value::as_u64)
                .or_else(|| item.get("sizeBytes").and_then(Value::as_u64))
                .unwrap_or(0);
            let filename = text(item.get("filename"));
            let content_id = text(item.get("contentId"));
            Attachment {
                index,
                filename: if filename.is_empty() { "attachment".into() } else { filename },
                mime_type: text(item.get("mimeType")),
                size,
                content_id: if content_id.is_empty() { None } else { Some(content_id) },
                // Only an explicit false: mail sealed before the field existed
                // always had a body.
                stored: item.get("stored").and_then(Value::as_bool).unwrap_or(true),
            }
        })
        .collect()
}

/// A message's key epoch: absent from servers before epochs, meaning 0.
fn key_epoch(wire: &Value) -> u32 {
    wire.get("keyEpoch").and_then(Value::as_u64).and_then(|e| u32::try_from(e).ok()).unwrap_or(0)
}

fn open_content(keys: Option<&Keys>, wire: &Value) -> Option<Value> {
    let keys = keys?;
    let content = wire.get("content").filter(|v| !v.is_null())?;
    let address_id = text(wire.get("inboxId"));
    let message_id = text(wire.get("id"));
    // The key for the epoch it was sealed under: 0 unless the address's keys were rotated.
    let epoch = key_epoch(wire);

    // An asymmetric box is the one with an ephemeral public key in it.
    if content.get("epk").and_then(Value::as_str).is_some() {
        let box_: AsymmetricBox = serde_json::from_value(content.clone()).ok()?;
        let private_key = keys.address_private_key_at(&address_id, epoch).ok()?;
        // The additional data binds the ciphertext to this address and this
        // message, exactly as the mail server sealed it.
        let plaintext =
            open_with_private_key(&private_key, &box_, &format!("{address_id}:{message_id}")).ok()?;
        serde_json::from_slice(&plaintext).ok()
    } else {
        let box_: SealedBox = serde_json::from_value(content.clone()).ok()?;
        let key = keys.address_symmetric_key_at(&address_id, epoch).ok()?;
        open_json(&key, &box_, &message_id).ok()
    }
}

pub fn to_message(keys: Option<&Keys>, wire: &Value) -> Message {
    let content = open_content(keys, wire);
    let body = content.clone().unwrap_or(Value::Null);
    let get = |key: &str| body.get(key);

    let html = {
        let primary = text(get("html"));
        if primary.is_empty() {
            text(get("bodyHtml"))
        } else {
            primary
        }
    };
    let from_address = {
        let primary = text(get("fromAddress"));
        if primary.is_empty() {
            address_of(get("from"))
        } else {
            primary
        }
    };
    let to = match get("to") {
        Some(Value::Array(items)) => address_of(items.first()),
        other => address_of(other),
    };
    let stripped = if html.is_empty() { None } else { Some(strip_remote_content(&html)) };
    let from_name = {
        let primary = text(get("fromName"));
        if primary.is_empty() {
            name_of(get("from"))
        } else {
            primary
        }
    };
    let reply_to = {
        let primary = text(get("replyTo"));
        if primary.is_empty() {
            from_address.clone()
        } else {
            primary
        }
    };
    let text_body = {
        let primary = text(get("text"));
        if primary.is_empty() {
            text(get("bodyText"))
        } else {
            primary
        }
    };
    let folder = {
        let primary = text(wire.get("folder"));
        if primary.is_empty() {
            "inbox".to_string()
        } else {
            primary
        }
    };

    Message {
        id: text(wire.get("id")),
        address_id: text(wire.get("inboxId")),
        received_at: text(wire.get("receivedAt")),
        read: wire.get("read").and_then(Value::as_bool).unwrap_or(false),
        starred: wire.get("starred").and_then(Value::as_bool).unwrap_or(false),
        folder,
        size_bytes: wire.get("sizeBytes").and_then(Value::as_u64).unwrap_or(0),
        sent_via: wire.get("sentVia").and_then(Value::as_str).map(str::to_string),
        key_epoch: key_epoch(wire),
        opened: content.is_some(),
        from_address,
        from_name,
        reply_to,
        to,
        subject: text(get("subject")),
        text: text_body,
        html,
        safe_html: stripped.as_ref().map(|s| s.html.clone()).unwrap_or_default(),
        blocked: stripped.map(|s| s.blocked).unwrap_or_default(),
        message_id: text(get("messageId")),
        attachments: attachments_of(get("attachments")),
    }
}

pub fn open_attachment_bytes(
    keys: &Keys,
    address_id: &str,
    message_id: &str,
    index: usize,
    data: &[u8],
) -> Result<Vec<u8>> {
    open_attachment_bytes_at(keys, address_id, message_id, index, 0, data)
}

/// The same, for a message sealed under a later key epoch.
pub fn open_attachment_bytes_at(
    keys: &Keys,
    address_id: &str,
    message_id: &str,
    index: usize,
    epoch: u32,
    data: &[u8],
) -> Result<Vec<u8>> {
    let private_key = keys.address_private_key_at(address_id, epoch)?;
    open_attachment_with_key(&private_key, address_id, &format!("{address_id}/{message_id}/{index}"), data)
}