Cotton code
439 lines · 16.2 KB · RustRaw
//! The email tools' `validateX` functions, hand-ported from `protocol.ts` with//! their refusal sentences unchanged.use cotton_core::rules::email_state::{EmailFolder, EmailStatePatch};use serde_json::{Map, Value};use crate::mcp::handlers::common::{    bounded_limit, fail, is_uuid, iso_timestamp, optional_boolean, optional_string, require_string,    Valid,};/// How many emails one ingest call may carry — mirrored in the tool schema.pub const INGEST_EMAILS_MAX_BATCH: usize = 100;/// How many ids one bulk state change may carry — mirrored in the tool schema.pub const UPDATE_EMAILS_MAX_BATCH: usize = 100;/// A plausible address: something@something, no whitespace. Deliberately loose/// — the mail already existed, so refusing an odd-but-real address would lose/// data over a formality.////// `/^[^\s@]+@[^\s@]+$/`, as a check rather than a regex: two non-empty runs/// with no whitespace, separated by exactly one `@`.pub fn is_address(value: &str) -> bool {    let mut parts = value.split('@');    let (Some(local), Some(domain), None) = (parts.next(), parts.next(), parts.next()) else {        return false;    };    !local.is_empty()        && !domain.is_empty()        && !local.chars().any(is_js_space)        && !domain.chars().any(is_js_space)}/// JavaScript's `\s`, which is the ECMAScript whitespace set plus the line/// terminators — the same set `cotton_store::protocol::js` calls whitespace,/// with `\n`, `\r`, `\u{2028}` and `\u{2029}` already in it.fn is_js_space(character: char) -> bool {    cotton_store::protocol::js::is_js_whitespace(character)}#[derive(Debug, Clone, PartialEq, Eq)]pub struct EmailAddressArg {    pub email: String,    pub name: Option<String>,}#[derive(Debug, Clone, PartialEq, Eq)]pub struct IngestEmailAttachmentArg {    pub name: String,    pub mime: Option<String>,    pub size: Option<i64>,    pub key: Option<String>,}/// A message's read and flagged state as a mailbox without Gmail's labels/// reports it (IMAP's `\Seen` and `\Flagged`).#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct MailFlags {    pub unread: bool,    pub starred: bool,}/// What the importer knew about the mailbox this message lives in.#[derive(Debug, Clone, PartialEq, Eq)]pub struct IngestEmailGmailArg {    pub id: String,    pub account: String,    pub labels: Vec<String>,}#[derive(Debug, Clone)]pub struct IngestEmailArg {    pub thread_key: String,    pub subject: String,    pub sent_at: String,    pub body: String,    pub message_id: Option<String>,    pub gmail: Option<IngestEmailGmailArg>,    /// v76 — the mailbox address this message was read from (IMAP or Gmail),    /// so a connection can count what it brought; `None` for mail an assistant    /// filed from elsewhere.    pub account: Option<String>,    /// The state an IMAP server without Gmail's labels reports; ignored when    /// `gmail` is set (its labels say it). Never from the MCP tool.    pub flags: Option<MailFlags>,    pub from: EmailAddressArg,    pub to: Vec<EmailAddressArg>,    pub cc: Vec<EmailAddressArg>,    pub bcc: Vec<EmailAddressArg>,    pub snippet: Option<String>,    pub attachments: Vec<IngestEmailAttachmentArg>,}#[derive(Debug, Clone)]pub struct ListEmailThreadsArgs {    pub participant: Option<String>,    pub sender: Option<String>,    pub unread_only: Option<bool>,    pub folder: EmailFolder,    pub limit: i64,}#[derive(Debug, Clone)]pub struct ReadEmailThreadArgs {    pub thread_id: String,    pub before: Option<String>,    /// The id half of the page cursor, paired with `before`.    ///    /// OPTIONAL, and additive on purpose: `before` alone keeps meaning exactly    /// what it has always meant (strictly older than that instant), so no    /// caller that already pages this tool changes behaviour. With both, the    /// cursor is a KEYSET and a page boundary that falls inside a group of    /// messages sharing one instant no longer drops the rest of that group.    pub before_id: Option<String>,    pub limit: i64,}#[derive(Debug, Clone)]pub struct UpdateEmailArgs {    pub id: Option<String>,    pub thread_id: Option<String>,    pub patch: EmailStatePatch,}#[derive(Debug, Clone)]pub struct UpdateEmailsArgs {    pub ids: Option<Vec<String>>,    pub thread_ids: Option<Vec<String>>,    pub patch: EmailStatePatch,}#[derive(Debug, Clone)]pub struct ListEmailSendersArgs {    pub folder: EmailFolder,    pub limit: i64,}fn validate_address(value: Option<&Value>, where_: &str) -> Valid<EmailAddressArg> {    let Some(Value::Object(raw)) = value else {        return fail(format!("{where_} must be an object with an email"));    };    let email = require_string(raw, "email");    match email {        Some(email) if is_address(&email) => Ok(EmailAddressArg {            email,            name: optional_string(raw, "name"),        }),        _ => fail(format!("{where_}.email must be an email address")),    }}fn validate_address_list(value: Option<&Value>, where_: &str) -> Valid<Vec<EmailAddressArg>> {    let Some(value) = value else {        return Ok(Vec::new());    };    let Some(items) = value.as_array() else {        return fail(format!("{where_} must be an array of {{ email, name? }}"));    };    let mut out = Vec::with_capacity(items.len());    for (index, entry) in items.iter().enumerate() {        out.push(validate_address(            Some(entry),            &format!("{where_}[{index}]"),        )?);    }    Ok(out)}/// The `gmail` block is NOT read here, and that is the TypeScript's own/// decision rather than an omission: `validateIngestEmails` never carries one,/// so an assistant filing mail from anywhere gets the columns' own defaults —/// read, in the inbox, nothing to push, which is the honest answer for mail no/// mailbox filed. The block reaches [`IngestEmailArg`] only from the INTERNAL/// caller, `gmailSync`, which is 2f's; the field is here so that worker has/// somewhere to put it rather than a second entry point to build.pub fn validate_ingest_emails(args: &Map<String, Value>) -> Valid<Vec<IngestEmailArg>> {    let Some(emails) = args.get("emails").and_then(Value::as_array) else {        return fail("emails must be a non-empty array");    };    if emails.is_empty() {        return fail("emails must be a non-empty array");    }    if emails.len() > INGEST_EMAILS_MAX_BATCH {        return fail(format!(            "at most {INGEST_EMAILS_MAX_BATCH} emails per call — split the batch and call again"        ));    }    let mut out = Vec::with_capacity(emails.len());    for (index, entry) in emails.iter().enumerate() {        let where_ = format!("emails[{index}]");        let Some(raw) = entry.as_object() else {            return fail(format!("{where_} must be an object"));        };        let Some(thread_key) = require_string(raw, "threadKey") else {            return fail(format!("{where_}.threadKey is required"));        };        let Some(subject) = raw.get("subject").and_then(Value::as_str) else {            return fail(format!("{where_}.subject is required (use \"\" for none)"));        };        let subject = subject.trim().to_string();        let sent_at = require_string(raw, "sentAt")            .as_deref()            .and_then(iso_timestamp);        let Some(sent_at) = sent_at else {            return fail(format!("{where_}.sentAt must be an ISO 8601 timestamp"));        };        let Some(body) = raw.get("body").and_then(Value::as_str) else {            return fail(format!("{where_}.body is required (use \"\" for none)"));        };        let from = validate_address(raw.get("from"), &format!("{where_}.from"))?;        let to = validate_address_list(raw.get("to"), &format!("{where_}.to"))?;        let cc = validate_address_list(raw.get("cc"), &format!("{where_}.cc"))?;        let bcc = validate_address_list(raw.get("bcc"), &format!("{where_}.bcc"))?;        let mut attachments = Vec::new();        if let Some(raw_attachments) = raw.get("attachments") {            let Some(items) = raw_attachments.as_array() else {                return fail(format!("{where_}.attachments must be an array"));            };            for (j, attachment) in items.iter().enumerate() {                let Some(attachment) = attachment.as_object() else {                    return fail(format!("{where_}.attachments[{j}] must be an object"));                };                let Some(name) = require_string(attachment, "name") else {                    return fail(format!("{where_}.attachments[{j}].name is required"));                };                let size = match attachment.get("size") {                    None | Some(Value::Null) => None,                    Some(value) => match value.as_f64() {                        Some(size) if size.fract() == 0.0 && size >= 0.0 => Some(size as i64),                        _ => {                            return fail(format!(                                "{where_}.attachments[{j}].size must be a whole number of bytes"                            ))                        }                    },                };                attachments.push(IngestEmailAttachmentArg {                    name,                    mime: optional_string(attachment, "mime"),                    size,                    key: optional_string(attachment, "key"),                });            }        }        out.push(IngestEmailArg {            thread_key,            subject,            sent_at,            body: body.to_string(),            message_id: optional_string(raw, "messageId"),            gmail: None,            account: None,            flags: None,            from,            to,            cc,            bcc,            snippet: optional_string(raw, "snippet"),            attachments,        });    }    Ok(out)}/// `folder`, defaulted to `all` — the tool's default is not the app's.fn email_folder_arg(args: &Map<String, Value>) -> Valid<EmailFolder> {    let Some(raw) = optional_string(args, "folder") else {        return Ok(EmailFolder::All);    };    match EmailFolder::parse(&raw) {        Some(folder) => Ok(folder),        None => fail(format!(            "folder must be one of {}",            EmailFolder::ALL                .iter()                .map(|folder| folder.as_str())                .collect::<Vec<_>>()                .join(", ")        )),    }}/// The four state fields, read off the flat argument object. An empty patch is/// REFUSED rather than treated as a no-op: a caller who sent none of them meant/// something, and doing nothing silently is the masked state the repo bans.fn email_state_patch_arg(args: &Map<String, Value>) -> Valid<EmailStatePatch> {    let patch = EmailStatePatch {        read: optional_boolean(args, "read")?,        starred: optional_boolean(args, "starred")?,        inbox: optional_boolean(args, "inbox")?,        bin: optional_boolean(args, "bin")?,    };    if patch.read.is_none()        && patch.starred.is_none()        && patch.inbox.is_none()        && patch.bin.is_none()    {        return fail(            "name at least one of read, starred, inbox or bin — there is nothing to change",        );    }    Ok(patch)}/// `uuidList` — deduped, capped, and refused by name when an entry is not one.fn uuid_list(args: &Map<String, Value>, key: &str, max: usize) -> Valid<Option<Vec<String>>> {    let Some(raw) = args.get(key) else {        return Ok(None);    };    let Some(items) = raw.as_array().filter(|items| !items.is_empty()) else {        return fail(format!("{key} must be a non-empty array of ids"));    };    if items.len() > max {        return fail(format!(            "at most {max} ids per call — split the batch and call again"        ));    }    let mut out: Vec<String> = Vec::with_capacity(items.len());    for entry in items {        match entry.as_str() {            Some(value) if is_uuid(value) => {                if !out.iter().any(|seen| seen == value) {                    out.push(value.to_string());                }            }            _ => {                return fail(format!(                    "{key} must hold ids from list_email_threads or read_email_thread"                ))            }        }    }    Ok(Some(out))}pub fn validate_list_email_threads(args: &Map<String, Value>) -> Valid<ListEmailThreadsArgs> {    let participant = optional_string(args, "participant");    if participant.as_deref().is_some_and(|one| !is_address(one)) {        return fail("participant must be an email address");    }    let sender = optional_string(args, "sender");    if sender.as_deref().is_some_and(|one| !is_address(one)) {        return fail("sender must be an email address");    }    Ok(ListEmailThreadsArgs {        participant: participant.map(|one| one.to_lowercase()),        sender: sender.map(|one| one.to_lowercase()),        unread_only: optional_boolean(args, "unreadOnly")?,        folder: email_folder_arg(args)?,        limit: bounded_limit(args, 50, crate::mcp::handlers::common::MAX_LIST),    })}pub fn validate_read_email_thread(args: &Map<String, Value>) -> Valid<ReadEmailThreadArgs> {    let thread_id = require_string(args, "threadId");    let Some(thread_id) = thread_id.filter(|one| is_uuid(one)) else {        return fail("threadId must be a thread id from list_email_threads");    };    let before = match optional_string(args, "before") {        None => None,        Some(raw) => match iso_timestamp(&raw) {            Some(parsed) => Some(parsed),            None => return fail("before must be an ISO 8601 timestamp"),        },    };    // The id half is an OPAQUE cursor the caller echoes back from    // `nextBeforeId`, not an id anybody types — so it is checked for being    // there and nothing else. `before` is validated because a malformed    // instant silently compares as text; an id that names no row simply    // matches nothing extra, and the SQL is parameterised either way.    let before_id = match optional_string(args, "beforeId") {        None => None,        Some(raw) if !raw.trim().is_empty() => Some(raw),        Some(_) => return fail("beforeId must be the nextBeforeId from a previous page"),    };    if before_id.is_some() && before.is_none() {        return fail("beforeId is the second half of a cursor — pass before with it");    }    Ok(ReadEmailThreadArgs {        thread_id,        before,        before_id,        limit: bounded_limit(args, 20, 50),    })}pub fn validate_update_email(args: &Map<String, Value>) -> Valid<UpdateEmailArgs> {    let id = optional_string(args, "id");    let thread_id = optional_string(args, "threadId");    if id.is_none() == thread_id.is_none() {        return fail("name exactly one of id (one message) or threadId (the whole conversation)");    }    let target = id.clone().or_else(|| thread_id.clone()).unwrap_or_default();    if !is_uuid(&target) {        return fail("id and threadId are ids from the email tools");    }    Ok(UpdateEmailArgs {        id,        thread_id,        patch: email_state_patch_arg(args)?,    })}pub fn validate_update_emails(args: &Map<String, Value>) -> Valid<UpdateEmailsArgs> {    let ids = uuid_list(args, "ids", UPDATE_EMAILS_MAX_BATCH)?;    let thread_ids = uuid_list(args, "threadIds", UPDATE_EMAILS_MAX_BATCH)?;    if ids.is_none() == thread_ids.is_none() {        return fail("name exactly one of ids (messages) or threadIds (conversations)");    }    Ok(UpdateEmailsArgs {        ids,        thread_ids,        patch: email_state_patch_arg(args)?,    })}pub fn validate_list_email_senders(args: &Map<String, Value>) -> Valid<ListEmailSendersArgs> {    Ok(ListEmailSendersArgs {        folder: email_folder_arg(args)?,        limit: bounded_limit(args, 50, crate::mcp::handlers::common::MAX_LIST),    })}/// `block_sender` and `unblock_sender` — one reading, lower-cased, because the/// address is an IDENTITY and `News@Acme.com` is the same sender as/// `news@acme.com`.pub fn validate_block_sender(args: &Map<String, Value>) -> Valid<String> {    match require_string(args, "address") {        Some(address) if is_address(&address) => Ok(address.to_lowercase()),        _ => fail("address must be an email address"),    }}#[cfg(test)]#[path = "validate_tests.rs"]mod tests;