Skip to main content

qualia_client_core/
mail_transport.rs

1//! SMTP send + IMAP fetch transport for the semantic mail client.
2//!
3//! This module is the **network edge** for mail: it puts bytes on the wire (SMTP over
4//! STARTTLS) and pulls unseen messages off it (IMAP over implicit TLS). It deliberately does
5//! *not* make delivery decisions — those belong to the pure rules layer in
6//! [`crate::mail_rules`]. The bridge between the two is [`build_inbound`], a pure function that
7//! constructs the [`crate::mail_rules::InboundMessage`] envelope the rules engine consumes; the
8//! IMAP path uses it to turn each fetched message into something [`crate::mail_rules::evaluate`]
9//! can rule on.
10//!
11//! Network functions are gated `#[cfg(not(target_arch = "wasm32"))]` — there is no raw-socket
12//! SMTP/IMAP on the `wasm32` target, so only the pure surface ([`SmtpConfig`], [`ImapConfig`],
13//! [`OutgoingMail`], [`build_inbound`]) compiles there.
14//!
15//! All fallible network functions map their underlying errors to `String` so callers get a flat,
16//! transport-agnostic error surface.
17
18use serde::{Deserialize, Serialize};
19
20/// Connection + credentials for an outbound SMTP submission server (STARTTLS on the submission port).
21#[derive(Debug, Clone, Serialize, Deserialize)]
22pub struct SmtpConfig {
23    /// The SMTP server hostname (e.g. `smtp.example.org`).
24    pub host: String,
25    /// The submission port (commonly `587` for STARTTLS).
26    pub port: u16,
27    /// The SMTP username (usually the full mailbox address).
28    pub username: String,
29    /// The SMTP password / app-password / token.
30    pub password: String,
31}
32
33/// Connection + credentials for an inbound IMAP server (implicit TLS on the IMAPS port).
34#[derive(Debug, Clone, Serialize, Deserialize)]
35pub struct ImapConfig {
36    /// The IMAP server hostname (e.g. `imap.example.org`).
37    pub host: String,
38    /// The IMAPS port (commonly `993` for implicit TLS).
39    pub port: u16,
40    /// The IMAP username (usually the full mailbox address).
41    pub username: String,
42    /// The IMAP password / app-password / token.
43    pub password: String,
44}
45
46/// Connection + credentials for a legacy POP3S service. POP3 is retrieval
47/// only; SMTP remains the outbound transport. Implicit TLS is required so the
48/// account password is never sent on a plaintext POP3 connection.
49#[derive(Debug, Clone, Serialize, Deserialize)]
50pub struct Pop3Config {
51    /// The POP3 server hostname (for example `pop.example.org`).
52    pub host: String,
53    /// POP3S is commonly served on port 995.
54    pub port: u16,
55    pub username: String,
56    pub password: String,
57}
58
59/// A message fetched through POP3S before semantic delivery rules decide its
60/// final local mailbox and quarantine state.
61#[derive(Debug, Clone)]
62pub struct Pop3FetchedMessage {
63    pub uid: String,
64    pub inbound: crate::mail_rules::InboundMessage,
65    pub body: String,
66}
67
68/// A message to be sent via [`send`].
69#[derive(Debug, Clone, Serialize, Deserialize)]
70pub struct OutgoingMail {
71    /// The sender address (`from`), e.g. `me@example.org`.
72    pub from: String,
73    /// The recipient address (`to`), e.g. `alice@example.org`.
74    pub to: String,
75    /// The subject line.
76    pub subject: String,
77    /// The plain-text body.
78    pub body: String,
79}
80
81/// Construct an [`InboundMessage`](crate::mail_rules::InboundMessage) envelope for the rules engine.
82///
83/// This is **pure**: it only populates the struct from its arguments — no I/O, no clock. It is the
84/// single place both real IMAP delivery and tests build the envelope the rules engine consumes, so
85/// the mapping from wire data to the rules' view lives in exactly one spot.
86pub fn build_inbound(
87    from: &str,
88    to: &str,
89    subject: &str,
90    size: usize,
91    sender_verified: bool,
92    sender_did: Option<String>,
93) -> crate::mail_rules::InboundMessage {
94    crate::mail_rules::InboundMessage {
95        from_address: from.to_string(),
96        to_address: to.to_string(),
97        sender_did,
98        sender_verified,
99        subject: subject.to_string(),
100        size_bytes: size,
101    }
102}
103
104/// Send `mail` through the SMTP submission server described by `cfg` (STARTTLS).
105///
106/// Builds a plain-text [`lettre::Message`], opens a pooled STARTTLS relay to `cfg.host:cfg.port`
107/// authenticating with `cfg.username` / `cfg.password`, and submits the message. All underlying
108/// errors (address parse, transport build, send) are flattened to `String`.
109#[cfg(not(target_arch = "wasm32"))]
110pub fn send(cfg: &SmtpConfig, mail: &OutgoingMail) -> Result<(), String> {
111    use lettre::transport::smtp::authentication::Credentials;
112    use lettre::{Message, SmtpTransport, Transport};
113
114    let from = mail
115        .from
116        .parse::<lettre::message::Mailbox>()
117        .map_err(|e| format!("invalid from address {:?}: {}", mail.from, e))?;
118    let to = mail
119        .to
120        .parse::<lettre::message::Mailbox>()
121        .map_err(|e| format!("invalid to address {:?}: {}", mail.to, e))?;
122
123    let msg: Message = Message::builder()
124        .from(from)
125        .to(to)
126        .subject(mail.subject.clone())
127        .body(mail.body.clone())
128        .map_err(|e| format!("failed to build message: {}", e))?;
129
130    let creds = Credentials::new(cfg.username.clone(), cfg.password.clone());
131
132    let transport = SmtpTransport::starttls_relay(&cfg.host)
133        .map_err(|e| format!("failed to build STARTTLS relay for {:?}: {}", cfg.host, e))?
134        .port(cfg.port)
135        .credentials(creds)
136        .build();
137
138    transport
139        .send(&msg)
140        .map(|_| ())
141        .map_err(|e| format!("SMTP send failed: {}", e))
142}
143
144/// Fetch the unseen messages from `mailbox` on the IMAP server described by `cfg` (implicit TLS).
145///
146/// Connects over implicit TLS to `cfg.host:cfg.port`, logs in, selects `mailbox`, searches for
147/// `UNSEEN` messages, and for each fetches `RFC822.SIZE ENVELOPE`. Each fetched message is turned
148/// into an [`InboundMessage`](crate::mail_rules::InboundMessage) via [`build_inbound`] using the
149/// envelope's `from` (first sender address, reconstructed as `local@host`) and `subject`, its
150/// reported size, and `mailbox` as the recipient. Because IMAP does not itself attest sender
151/// identity, `sender_verified` is `false` and `sender_did` is `None`; verification is a higher-layer
152/// concern. The session is logged out before returning. This is written defensively — a message with
153/// no envelope or no size is skipped rather than failing the whole fetch — and all underlying errors
154/// are flattened to `String`.
155#[cfg(not(target_arch = "wasm32"))]
156pub fn fetch_unseen(
157    cfg: &ImapConfig,
158    mailbox: &str,
159) -> Result<Vec<crate::mail_rules::InboundMessage>, String> {
160    let tls = native_tls::TlsConnector::builder()
161        .build()
162        .map_err(|e| format!("failed to build TLS connector: {}", e))?;
163
164    let client = imap::connect((cfg.host.as_str(), cfg.port), &cfg.host, &tls)
165        .map_err(|e| format!("IMAP connect to {:?}:{} failed: {}", cfg.host, cfg.port, e))?;
166
167    let mut session = client
168        .login(&cfg.username, &cfg.password)
169        // On login failure imap returns (Error, Client); keep only the error text.
170        .map_err(|e| format!("IMAP login failed: {}", e.0))?;
171
172    // Ensure we log out even if a later step fails.
173    let result = (|| -> Result<Vec<crate::mail_rules::InboundMessage>, String> {
174        session
175            .select(mailbox)
176            .map_err(|e| format!("IMAP SELECT {:?} failed: {}", mailbox, e))?;
177
178        let unseen = session
179            .search("UNSEEN")
180            .map_err(|e| format!("IMAP SEARCH UNSEEN failed: {}", e))?;
181
182        let mut out: Vec<crate::mail_rules::InboundMessage> = Vec::with_capacity(unseen.len());
183
184        for uid in unseen {
185            // Fetch by sequence number; ask only for the envelope + size.
186            let fetches = match session.fetch(uid.to_string(), "RFC822.SIZE ENVELOPE") {
187                Ok(f) => f,
188                // Be defensive: skip a message that can't be fetched rather than aborting all.
189                Err(_) => continue,
190            };
191
192            for fetch in fetches.iter() {
193                let envelope = match fetch.envelope() {
194                    Some(e) => e,
195                    None => continue,
196                };
197
198                // Subject — envelope fields are raw bytes; decode lossily.
199                let subject = envelope
200                    .subject
201                    .as_ref()
202                    .map(|s| String::from_utf8_lossy(s).into_owned())
203                    .unwrap_or_default();
204
205                // Reconstruct `local@host` from raw IMAP mailbox/host byte fields.
206                let parts_to_string =
207                    |mailbox_bytes: Option<&[u8]>, host_bytes: Option<&[u8]>| -> String {
208                        let mailbox_part = mailbox_bytes
209                            .map(|m| String::from_utf8_lossy(m).into_owned())
210                            .unwrap_or_default();
211                        let host_part = host_bytes
212                            .map(|h| String::from_utf8_lossy(h).into_owned())
213                            .unwrap_or_default();
214                        if host_part.is_empty() {
215                            mailbox_part
216                        } else {
217                            format!("{mailbox_part}@{host_part}")
218                        }
219                    };
220
221                // From — first sender address, if present.
222                let from = envelope
223                    .from
224                    .as_ref()
225                    .and_then(|addrs| addrs.first())
226                    .map(|addr| {
227                        parts_to_string(
228                            addr.mailbox.as_ref().map(|m| m.as_ref()),
229                            addr.host.as_ref().map(|h| h.as_ref()),
230                        )
231                    })
232                    .unwrap_or_default();
233
234                // To — first envelope recipient when it looks like an address; else IMAP folder
235                // name (often "INBOX"). mail_fetch falls back to IMAP username for non-@ targets.
236                let to = envelope
237                    .to
238                    .as_ref()
239                    .and_then(|addrs| addrs.first())
240                    .map(|addr| {
241                        parts_to_string(
242                            addr.mailbox.as_ref().map(|m| m.as_ref()),
243                            addr.host.as_ref().map(|h| h.as_ref()),
244                        )
245                    })
246                    .filter(|s| s.contains('@'))
247                    .unwrap_or_else(|| mailbox.to_string());
248
249                // Size — `RFC822.SIZE` populates `fetch.size`; default to 0 when absent.
250                let size = fetch.size.unwrap_or(0) as usize;
251
252                out.push(build_inbound(
253                    &from, &to, &subject, size,
254                    false, // sender_verified — IMAP does not attest identity
255                    None,  // sender_did — verification is a higher-layer concern
256                ));
257            }
258        }
259
260        Ok(out)
261    })();
262
263    // Best-effort logout; the fetch result takes precedence.
264    let _ = session.logout();
265
266    result
267}
268
269/// Retrieve messages from a traditional POP3S mailbox. POP3 has no portable
270/// `UNSEEN` flag, so this returns the mailbox contents; the caller is expected
271/// to persist accepted UIDLs before the next poll. Only implicit TLS is
272/// supported—plaintext POP3 would expose the account password.
273#[cfg(not(target_arch = "wasm32"))]
274pub fn fetch_pop3(cfg: &Pop3Config, mailbox: &str) -> Result<Vec<Pop3FetchedMessage>, String> {
275    use std::io::{BufRead, BufReader, Write};
276    use std::net::TcpStream;
277
278    fn response_line<S: std::io::Read>(reader: &mut BufReader<S>) -> Result<String, String> {
279        let mut line = String::new();
280        reader
281            .read_line(&mut line)
282            .map_err(|e| format!("POP3 read failed: {e}"))?;
283        if !line.starts_with("+OK") {
284            return Err(format!("POP3 rejected command: {}", line.trim()));
285        }
286        Ok(line)
287    }
288    fn command<S: std::io::Read + Write>(
289        reader: &mut BufReader<S>,
290        command: &str,
291    ) -> Result<(), String> {
292        reader
293            .get_mut()
294            .write_all(command.as_bytes())
295            .map_err(|e| format!("POP3 write failed: {e}"))?;
296        reader
297            .get_mut()
298            .flush()
299            .map_err(|e| format!("POP3 flush failed: {e}"))?;
300        response_line(reader).map(|_| ())
301    }
302    fn multiline<S: std::io::Read>(reader: &mut BufReader<S>) -> Result<Vec<String>, String> {
303        let mut lines = Vec::new();
304        loop {
305            let mut line = String::new();
306            reader
307                .read_line(&mut line)
308                .map_err(|e| format!("POP3 read failed: {e}"))?;
309            let line = line.trim_end_matches(['\r', '\n']).to_string();
310            if line == "." {
311                break;
312            }
313            lines.push(line.strip_prefix("..").unwrap_or(&line).to_string());
314        }
315        Ok(lines)
316    }
317    fn headers_and_body(lines: &[String]) -> (String, String, String, String) {
318        let mut from = String::new();
319        let mut to = String::new();
320        let mut subject = String::new();
321        let mut body_at = lines.len();
322        for (index, line) in lines.iter().enumerate() {
323            if line.is_empty() {
324                body_at = index + 1;
325                break;
326            }
327            if let Some(value) = line
328                .strip_prefix("From:")
329                .or_else(|| line.strip_prefix("from:"))
330            {
331                from = value.trim().to_string();
332            }
333            if let Some(value) = line
334                .strip_prefix("To:")
335                .or_else(|| line.strip_prefix("to:"))
336            {
337                to = value.trim().to_string();
338            }
339            if let Some(value) = line
340                .strip_prefix("Subject:")
341                .or_else(|| line.strip_prefix("subject:"))
342            {
343                subject = value.trim().to_string();
344            }
345        }
346        (from, to, subject, lines[body_at..].join("\n"))
347    }
348
349    let tcp = TcpStream::connect((cfg.host.as_str(), cfg.port))
350        .map_err(|e| format!("POP3S connect to {}:{} failed: {e}", cfg.host, cfg.port))?;
351    let tls = native_tls::TlsConnector::builder()
352        .build()
353        .map_err(|e| format!("POP3S TLS setup failed: {e}"))?;
354    let stream = tls
355        .connect(&cfg.host, tcp)
356        .map_err(|e| format!("POP3S TLS connect failed: {e}"))?;
357    let mut reader = BufReader::new(stream);
358    response_line(&mut reader)?;
359    command(&mut reader, &format!("USER {}\r\n", cfg.username))?;
360    command(&mut reader, &format!("PASS {}\r\n", cfg.password))?;
361    command(&mut reader, "UIDL\r\n")?;
362    let uids = multiline(&mut reader)?;
363    let mut messages = Vec::new();
364    for entry in uids {
365        let mut parts = entry.split_whitespace();
366        let Some(number) = parts.next() else {
367            continue;
368        };
369        let Some(uid) = parts.next() else {
370            continue;
371        };
372        command(&mut reader, &format!("RETR {number}\r\n"))?;
373        let lines = multiline(&mut reader)?;
374        let (from, mut to, subject, body) = headers_and_body(&lines);
375        if !to.contains('@') {
376            to = mailbox.to_string();
377        }
378        let inbound = build_inbound(&from, &to, &subject, body.len(), false, None);
379        messages.push(Pop3FetchedMessage {
380            uid: uid.to_string(),
381            inbound,
382            body,
383        });
384    }
385    let _ = command(&mut reader, "QUIT\r\n");
386    Ok(messages)
387}
388
389#[cfg(test)]
390mod tests {
391    use super::*;
392
393    #[test]
394    fn build_inbound_populates_fields() {
395        let msg = build_inbound(
396            "alice@example.org",
397            "me@example.org",
398            "Hello there",
399            2048,
400            true,
401            Some("did:example:alice".to_string()),
402        );
403
404        assert_eq!(msg.from_address, "alice@example.org");
405        assert_eq!(msg.to_address, "me@example.org");
406        assert_eq!(msg.subject, "Hello there");
407        assert_eq!(msg.size_bytes, 2048);
408        assert!(msg.sender_verified);
409        assert_eq!(msg.sender_did.as_deref(), Some("did:example:alice"));
410    }
411
412    #[test]
413    fn build_inbound_defaults_unverified_no_did() {
414        let msg = build_inbound("spam@nowhere.test", "junk@example.org", "", 0, false, None);
415
416        assert_eq!(msg.from_address, "spam@nowhere.test");
417        assert_eq!(msg.to_address, "junk@example.org");
418        assert_eq!(msg.subject, "");
419        assert_eq!(msg.size_bytes, 0);
420        assert!(!msg.sender_verified);
421        assert!(msg.sender_did.is_none());
422    }
423}