Cotton code
628 lines · 26.9 KB · RustRaw
//! THE WIRE CONTRACT with the server's message import — the port of//! `packages/import-core/src/envelope.ts`.//!//! Specs: `2026-08-16-cotton-group-mirror-design.md` §2 (shape),//! `2026-08-25-cotton-whatsapp-import-identity-design.md` §6 (identity//! fields).//!//! These types are DUPLICATED from the service on purpose. The service owns//! the schema and the writes; this package owns the parsers, and importing the//! whole domain layer from here would make the parser depend on it. The//! validator below is the executable restatement on the producing side.//!//! Every field is camelCase. The first shipped version of the TypeScript sent//! snake_case message fields while the function read camelCase — both sides//! had green tests in their own spelling and no test crossed the seam, so//! every real `--execute` 400'd. Hence the seam test, and hence this comment.//!//! ## What the port could not keep, and what it gained//!//! The validators take a `serde_json::Value`, not a typed struct, because//! their whole job is to describe a value that may be ANY shape — a typed//! argument would answer the question by refusing to hold the wrong answer.//! Rust does distinguish an ABSENT key from an explicit `null` here, exactly//! as JavaScript's `!== undefined` does, so `{ "phone": null }` is a reported//! problem on both sides while an omitted `phone` is fine on both.//!//! Rust has no default arguments, so `at` and `context` are always passed;//! `"message"` and `EnvelopeKind::Dm` are the TypeScript's defaults.use std::sync::OnceLock;use crate::js;use regex::Regex;use serde::{Deserialize, Serialize};use serde_json::{Map, Value};use crate::import::text::js_trim;/// Whose side of the conversation a message came from.#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "lowercase")]pub enum Direction {    In,    Out,}impl Direction {    pub const fn as_str(self) -> &'static str {        match self {            Direction::In => "in",            Direction::Out => "out",        }    }}/// `{emoji, actor: '<e164>'|'owner', at?: iso}` per the `reactions` column.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct EnvelopeReaction {    pub emoji: String,    /// Canonical phone (digits, no `+`) or the literal `"owner"`.    pub actor: String,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub at: Option<String>,}/// One attachment on a message.////// A media-store object key names bytes already owned by the importing device.#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase", deny_unknown_fields)]pub struct EnvelopeMedia {    pub key: String,    pub content_type: String,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub name: Option<String>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub size_bytes: Option<f64>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub width: Option<f64>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub height: Option<f64>,    /// A shared contact card's readable part, when the attachment is a `.vcf`.    /// Left as a `Value` here so `vcard`'s port owns that shape alone.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub contact: Option<Value>,    /// A recording's length.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub duration_ms: Option<f64>,    /// A second object holding the same recording in a container the phone    /// plays (a voice note's AAC m4a beside its Ogg original).    #[serde(default, skip_serializing_if = "Option::is_none")]    pub playback_key: Option<String>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub playback_content_type: Option<String>,    /// A sealed table's file (sealing plan L8): the per-file key the bytes    /// under `key` (a random `<database>/sealed/<hex>`) open with, base64url.    /// It travels only inside the row's sealed blob.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub file_key: Option<String>,    /// What the attachment is, where its MIME type does not say (a voice note is    /// `voice`, not `audio`). The Mac copies it from the outbox row it sent    /// (CONTRACT "WhatsApp through the Mac", pictures, voice notes and video):    /// none from an older Mac, and the reader falls back on the MIME type.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub kind: Option<crate::messages::MessageMediaKind>,    /// A voice note's peaks, each 0..1, as the phone recorded them (the outbox    /// row's 64 WhatsApp bytes, each over 100).    #[serde(default, skip_serializing_if = "Option::is_none")]    pub waveform: Option<Vec<f64>>,    /// A picture's or a video's small preview, as the phone made it (base64    /// JPEG), so the sent message draws at once before its file is fetched.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub preview: Option<String>,}/// One message, as the server's import expects to receive it.////// The field order below is the TypeScript INTERFACE's, which is not the order/// its two object literals insert keys in. Neither order is observable: the/// batch is parsed as JSON by the server, and `external_id` is computed from/// the body and the instant alone.// NOT `Eq`. An attachment carries `sizeBytes`, `width` and `height` as JSON// numbers, which are `f64` here — and a float has no total equality, so a// message that can hold one cannot claim `Eq` either. `PartialEq` is what every// caller actually asks for.#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct EnvelopeMessage {    /// Canonical phone of the CONTACT (never the owner) — dm batches only, and    /// only when the counterpart is known; a dm against an unidentified person    /// carries none (the batch's `dm` block names them).    #[serde(default, skip_serializing_if = "Option::is_none")]    pub phone: Option<String>,    /// dm batches: the counterpart's email, when THAT is what the source knew    /// (schema v36).    ///    /// The TypeScript's shape is split across two files, exactly as it is for    /// [`EnvelopeThreadParticipant`]: the wire envelope this is a port of never    /// grew the field, because WhatsApp has no such identity, while the import    /// ENGINE's `ImportEnvelope` does — and an iMessage counterpart is an Apple    /// ID, half of which are an address rather than a number. ONE message type    /// here carrying both, rather than a second one that differs by a column;    /// `handle_from` prefers the phone when a message names both.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub email: Option<String>,    /// Group batches: who sent an inbound message — the label the export    /// wrote, one of the thread block's participants. Absent for    /// `direction: "out"` (the owner) and for system lines (`meta.system`).    #[serde(default, skip_serializing_if = "Option::is_none")]    pub sender_label: Option<String>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub display_name: Option<String>,    pub direction: Direction,    pub body: String,    /// Uploaded attachments. Empty/absent when nothing was uploaded.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub media: Option<Vec<EnvelopeMedia>>,    /// ISO-8601 instant.    pub sent_at: String,    /// Idempotency key — the source's real id where one exists, else the    /// content fingerprint.    pub external_id: String,    /// Raw channel-side id of the quoted message; the server resolves what it    /// can.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub reply_to_external_id: Option<String>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub reactions: Option<Vec<EnvelopeReaction>>,    /// Descriptive flags only (edited / system / attachment), never behaviour.    ///    /// A `serde_json::Map`, insertion-ordered (the workspace turns on    /// serde_json's `preserve_order`), because the meta an importer builds is    /// stored as JSON text.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub meta: Option<Map<String, Value>>,}/// A source's handle before normalisation, using the same kinds as People.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase", deny_unknown_fields)]pub struct EnvelopeHandle {    pub kind: crate::handles::HandleKind,    pub value: String,}/// One person in a thread, as the export names them. The label is what the/// export wrote — a saved name, or the number of an unsaved contact. A phone/// and a person are attached when the caller could match the label; without/// them the person imports UNIDENTIFIED and can be named from the chat later.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct EnvelopeThreadParticipant {    pub label: String,    /// Canonical phone (digits, no `+`).    #[serde(default, skip_serializing_if = "Option::is_none")]    pub phone: Option<String>,    /// Their email, when that is the identity the source carried.    ///    /// Schema v36, and the TypeScript's shape is split across two files: the    /// wire envelope this is a port of never grew the field, because WhatsApp    /// has no such identity, while the import ENGINE's `ImportParticipant`    /// does — and the Mac's Messages reader, which hands the engine an Apple    /// ID as readily as a number, is why. One participant type here carrying    /// both, rather than a second one that differs by a column.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub email: Option<String>,    /// The People record this label is known to be.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub person_id: Option<String>,    /// A site's identity; a display name supplies no membership authority.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub handle: Option<EnvelopeHandle>,}/// The other side of a dm — same shape, one person.pub type EnvelopeCounterpart = EnvelopeThreadParticipant;/// Group-thread identity. Absent for dm batches — the server keeps its dm path/// when there is no thread block.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct EnvelopeThread {    /// Always the literal `"group"`; the validator refuses anything else.    pub kind: String,    pub title: String,    /// Stable import identity, `wa:group:<slug>` — how re-imports find the    /// thread.    pub external_key: String,    pub participants: Vec<EnvelopeThreadParticipant>,}/// The POST body. `workspace_id` is there because the route validates/// workspace ownership; `channel` because the envelope items carry none and/// every row this importer writes is `channel='whatsapp'`. Both are/// batch-level rather than per-message so a 500-message body does not repeat/// two constants 500 times.// NOT `Eq`, for the reason `EnvelopeMessage` is not: an attachment's// `sizeBytes`, `width` and `height` are JSON numbers, so a float rides all the// way up here and a float has no total equality.#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct ImportBatch {    pub workspace_id: String,    pub channel: String,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub thread: Option<EnvelopeThread>,    /// dm batches: who the other side is. Required when the messages carry no    /// `phone`.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub dm: Option<EnvelopeCounterpart>,    pub messages: Vec<EnvelopeMessage>,    /// The id to use IF this run has to create the thread.    ///    /// A message attachment's object key carries its thread    /// (`{ws}/messages/{threadId}/{sha}.{ext}`), so "which thread is this?"    /// has to be answered before a byte moves — it cannot wait for the insert.    /// So the caller reserves the id and the writer honours it only when it is    /// the one creating the thread; an existing conversation always keeps its    /// own. Ignored on a batch that resolves more than one thread.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub new_thread_id: Option<String>,}/// Batches are capped so one request stays inside the route's budget.pub const MAX_BATCH_MESSAGES: usize = 500;fn iso_instant() -> &'static Regex {    static RE: OnceLock<Regex> = OnceLock::new();    RE.get_or_init(|| {        Regex::new(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:\d{2})$")            .expect("iso instant")    })}fn uuid() -> &'static Regex {    static RE: OnceLock<Regex> = OnceLock::new();    RE.get_or_init(|| {        Regex::new(r"(?i)^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$")            .expect("uuid")    })}fn phone_pattern() -> &'static Regex {    static RE: OnceLock<Regex> = OnceLock::new();    RE.get_or_init(|| Regex::new(r"^[0-9]{8,15}$").expect("phone"))}/// JS `isRecord` — an object that is not an array. `null` is not one.fn as_record(value: &Value) -> Option<&Map<String, Value>> {    value.as_object()}/// `${JSON.stringify(x)}` inside a template literal, including the `undefined`/// a missing key interpolates to. That word reaches a human reading a failed/// import, so it is part of the contract, not an implementation detail.fn stringify(value: Option<&Value>) -> String {    match value {        Some(value) => js::json_stringify(value),        None => "undefined".to_string(),    }}/// How strict to be about identity fields, decided by the batch's thread block.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum EnvelopeKind {    Dm,    Group,}fn is_string(value: Option<&Value>) -> bool {    matches!(value, Some(Value::String(_)))}fn string_of(value: Option<&Value>) -> Option<&str> {    match value {        Some(Value::String(text)) => Some(text.as_str()),        _ => None,    }}/// Structural validation of one envelope item. Returns human-readable/// problems; an empty list means "conforms to the contract". Deliberately NOT/// a parse that fails — the CLI wants to report every problem in a run, not/// die on the first.pub fn validate_envelope_message(value: &Value, at: &str, context: EnvelopeKind) -> Vec<String> {    let mut issues: Vec<String> = Vec::new();    let Some(record) = as_record(value) else {        return vec![format!("{at}: expected an object")];    };    if context == EnvelopeKind::Dm {        if let Some(phone) = record.get("phone") {            let ok = string_of(Some(phone)).is_some_and(|text| phone_pattern().is_match(text));            if !ok {                issues.push(format!(                    "{at}.phone: expected 8–15 digits with no leading \"+\", got {}",                    stringify(Some(phone))                ));            }        }        if record.contains_key("senderLabel") {            issues.push(format!(                "{at}.senderLabel: only group batches carry senders"            ));        }    } else {        if record.contains_key("phone") {            issues.push(format!(                "{at}.phone: group batches identify people via senderLabel, not phone"            ));        }        let is_system = record            .get("meta")            .and_then(as_record)            .and_then(|meta| meta.get("system"))            == Some(&Value::Bool(true));        if record.get("direction") == Some(&Value::String("in".to_string())) && !is_system {            let label = record.get("senderLabel");            let ok = string_of(label).is_some_and(|text| !js_trim(text).is_empty());            if !ok {                issues.push(format!(                    "{at}.senderLabel: inbound group messages need the sender's label, got {}",                    stringify(label)                ));            }        } else if record.contains_key("senderLabel") {            issues.push(format!(                "{at}.senderLabel: only inbound non-system messages carry a sender"            ));        }    }    if record.contains_key("displayName") && !is_string(record.get("displayName")) {        issues.push(format!("{at}.displayName: expected a string when present"));    }    let direction = record.get("direction");    if direction != Some(&Value::String("in".to_string()))        && direction != Some(&Value::String("out".to_string()))    {        issues.push(format!(            "{at}.direction: expected \"in\" | \"out\", got {}",            stringify(direction)        ));    }    if !is_string(record.get("body")) {        issues.push(format!("{at}.body: expected a string"));    }    let sent_at = record.get("sentAt");    if !string_of(sent_at).is_some_and(|text| iso_instant().is_match(text)) {        issues.push(format!(            "{at}.sentAt: expected an ISO-8601 instant, got {}",            stringify(sent_at)        ));    }    if !string_of(record.get("externalId")).is_some_and(|text| !text.is_empty()) {        issues.push(format!("{at}.externalId: expected a non-empty string"));    }    if record.contains_key("replyToExternalId") && !is_string(record.get("replyToExternalId")) {        issues.push(format!(            "{at}.replyToExternalId: expected a string when present"        ));    }    if let Some(media) = record.get("media") {        match media.as_array() {            None => issues.push(format!("{at}.media: expected an array when present")),            Some(items) => {                for (index, item) in items.iter().enumerate() {                    let where_ = format!("{at}.media[{index}]");                    let Some(item) = as_record(item) else {                        issues.push(format!("{where_}: expected an object"));                        continue;                    };                    let has_key = string_of(item.get("key")).is_some_and(|text| !text.is_empty());                    if !has_key {                        issues.push(format!(                            "{where_}: expected a non-empty \"key\""                        ));                    }                    if !string_of(item.get("contentType")).is_some_and(|text| !text.is_empty()) {                        issues.push(format!("{where_}.contentType: expected a non-empty string"));                    }                    for field in ["sizeBytes", "width", "height", "durationMs"] {                        if let Some(present) = item.get(field) {                            if !present.is_number() {                                issues.push(format!(                                    "{where_}.{field}: expected a number when present"                                ));                            }                        }                    }                    if item.contains_key("name") && !is_string(item.get("name")) {                        issues.push(format!("{where_}.name: expected a string when present"));                    }                    for field in ["playbackKey", "playbackContentType"] {                        if item.contains_key(field) && !is_string(item.get(field)) {                            issues.push(format!("{where_}.{field}: expected a string when present"));                        }                    }                }            }        }    }    let body_empty = string_of(record.get("body")).is_some_and(|text| js_trim(text).is_empty());    let media_empty = record        .get("media")        .and_then(Value::as_array)        .is_none_or(|items| items.is_empty());    // A media-only message whose bytes were left behind keeps an empty body    // and says what it carried in its mark (`meta.mediaOnly`); a row with no    // words, no media and no mark says nothing at all.    let marked = record        .get("meta")        .and_then(as_record)        .and_then(crate::messages::media_only::media_only_kind)        .is_some_and(|kind| !kind.is_empty());    if body_empty && media_empty && !marked {        issues.push(format!(            "{at}.body: empty with no media and no mediaOnly mark — a message says something"        ));    }    if let Some(reactions) = record.get("reactions") {        match reactions.as_array() {            None => issues.push(format!("{at}.reactions: expected an array when present")),            Some(items) => {                for (index, reaction) in items.iter().enumerate() {                    let where_ = format!("{at}.reactions[{index}]");                    let Some(reaction) = as_record(reaction) else {                        issues.push(format!("{where_}: expected an object"));                        continue;                    };                    if !string_of(reaction.get("emoji")).is_some_and(|text| !text.is_empty()) {                        issues.push(format!("{where_}.emoji: expected a non-empty string"));                    }                    if !string_of(reaction.get("actor")).is_some_and(|text| !text.is_empty()) {                        issues.push(format!(                            "{where_}.actor: expected \"owner\" or a canonical phone"                        ));                    }                    if let Some(at_value) = reaction.get("at") {                        let ok = string_of(Some(at_value))                            .is_some_and(|text| iso_instant().is_match(text));                        if !ok {                            issues.push(format!(                                "{where_}.at: expected an ISO-8601 instant when present"                            ));                        }                    }                }            }        }    }    if let Some(meta) = record.get("meta") {        if as_record(meta).is_none() {            issues.push(format!("{at}.meta: expected an object when present"));        }    }    issues}fn validate_participant(participant: &Map<String, Value>, where_: &str) -> Vec<String> {    let mut issues = Vec::new();    if !string_of(participant.get("label")).is_some_and(|text| !js_trim(text).is_empty()) {        issues.push(format!("{where_}.label: expected a non-empty string"));    }    if let Some(phone) = participant.get("phone") {        let ok = string_of(Some(phone)).is_some_and(|text| phone_pattern().is_match(text));        if !ok {            issues.push(format!(                "{where_}.phone: expected 8–15 digits with no leading \"+\" when present"            ));        }    }    if let Some(person_id) = participant.get("personId") {        let ok = string_of(Some(person_id)).is_some_and(|text| !text.is_empty());        if !ok {            issues.push(format!(                "{where_}.personId: expected a non-empty string when present"            ));        }    }    issues}/// Structural validation of a whole POST body, including the batch cap.pub fn validate_import_batch(value: &Value) -> Vec<String> {    let Some(record) = as_record(value) else {        return vec!["batch: expected an object".to_string()];    };    let mut issues: Vec<String> = Vec::new();    let workspace = record.get("workspaceId");    if !string_of(workspace).is_some_and(|text| uuid().is_match(text)) {        issues.push(format!(            "batch.workspaceId: expected a uuid, got {}",            stringify(workspace)        ));    }    let channel = record.get("channel");    if !matches!(channel.and_then(Value::as_str), Some("whatsapp" | "instagram")) {        issues.push(format!(            "batch.channel: expected \"whatsapp\" or \"instagram\", got {}",            stringify(channel)        ));    }    let mut context = EnvelopeKind::Dm;    if let Some(thread) = record.get("thread") {        match as_record(thread) {            None => issues.push("batch.thread: expected an object when present".to_string()),            Some(thread) => {                context = EnvelopeKind::Group;                if thread.get("kind") != Some(&Value::String("group".to_string())) {                    issues.push(format!(                        "batch.thread.kind: expected \"group\", got {}",                        stringify(thread.get("kind"))                    ));                }                if !string_of(thread.get("title")).is_some_and(|text| !js_trim(text).is_empty()) {                    issues.push("batch.thread.title: expected a non-empty string".to_string());                }                if !string_of(thread.get("externalKey"))                    .is_some_and(|text| !js_trim(text).is_empty())                {                    issues                        .push("batch.thread.externalKey: expected a non-empty string".to_string());                }                // The participants are the people this batch's inbound                // messages name, so a page of a group holding only the                // owner's own messages carries none: an empty list is a list.                match thread.get("participants").and_then(Value::as_array) {                    None => issues.push("batch.thread.participants: expected an array".to_string()),                    Some(items) => {                        for (index, participant) in items.iter().enumerate() {                            let where_ = format!("batch.thread.participants[{index}]");                            match as_record(participant) {                                None => issues.push(format!("{where_}: expected an object")),                                Some(participant) => {                                    issues.extend(validate_participant(participant, &where_));                                }                            }                        }                    }                }            }        }    }    if let Some(dm) = record.get("dm") {        if as_record(dm).is_none() {            issues.push("batch.dm: expected an object when present".to_string());        } else if record.contains_key("thread") {            issues.push("batch.dm: a batch is a dm or a group, not both".to_string());        } else {            issues.extend(validate_participant(                as_record(dm).expect("checked above"),                "batch.dm",            ));        }    }    let Some(messages) = record.get("messages").and_then(Value::as_array) else {        issues.push("batch.messages: expected an array".to_string());        return issues;    };    if messages.is_empty() {        issues.push("batch.messages: expected at least one message".to_string());    }    if messages.len() > MAX_BATCH_MESSAGES {        issues.push(format!(            "batch.messages: {} exceeds the {MAX_BATCH_MESSAGES}-message cap",            messages.len()        ));    }    for (index, message) in messages.iter().enumerate() {        issues.extend(validate_envelope_message(            message,            &format!("messages[{index}]"),            context,        ));    }    issues}#[cfg(test)]#[path = "envelope_tests.rs"]mod tests;