diff --git a/docs/BACKEND.md b/docs/BACKEND.md index 0c80890e0..459046b54 100644 --- a/docs/BACKEND.md +++ b/docs/BACKEND.md @@ -159,6 +159,24 @@ subject to account capabilities. Search syntax follows the account's provider. List results include `accountId`, `messages`, `nextPageToken`, and `estimate`; an empty next-page token ends pagination. `read` returns safe text and attachment metadata without marking the message read or exporting attachment files. +The `message.links` array contains `{text, url}` entries from HTML anchors in the sanitized document, including links whose destination is absent from the plain-text body. Plain-text URLs remain in `nativeContent.body.text`; they are not separately extracted. `message.unsubscribe` contains `urls` from `List-Unsubscribe` and a `oneClick` boolean for the sender's `List-Unsubscribe-Post: List-Unsubscribe=One-Click` declaration when an HTTPS target is available. Missing metadata produces empty arrays and `oneClick: false`; providers can only expose metadata they supply. These additive fields are available in builds containing the read-link projection. + +Destinations are data only: extracting them does not resolve their DNS, open a browser, fetch links, send unsubscribe mail or submit an unsubscribe POST. Exported destinations are absolute HTTP(S) links passing the reader's public-host spelling policy, or nonempty `mailto:` links; controls, whitespace, backslashes and HTTP credentials are refused. This is not a DNS/public-address guarantee or sender authentication. `oneClick` reports a declaration, not authorization or proof of DKIM coverage. A caller executing a request must independently enforce its network and approval policy. Raw HTML, other headers, image/resource URLs and document attributes remain excluded. + +For example, `omamail read MESSAGE_ID --account ACCOUNT_ID --json` now includes: + +```json +{ + "links": [{"text": "Unsubscribe", "url": "https://news.example.org/leave"}], + "unsubscribe": { + "urls": ["https://news.example.org/leave", "mailto:leave@example.org"], + "oneClick": true + } +} +``` + +The fragment above is under `result.message` in CLI JSON output (under `message` in the `mail.read` RPC result). + `mark` accepts exactly `read`, `unread`, `star`, and `unstar`. Actions accept multiple message IDs. Their previews retain `requestedIds` and show the resolved `targetIds`, including expanded conversation members where applicable. diff --git a/src/mail/mod.rs b/src/mail/mod.rs index b2b820bac..0660e8d6a 100644 --- a/src/mail/mod.rs +++ b/src/mail/mod.rs @@ -2,6 +2,7 @@ mod account; pub(crate) mod action; pub(crate) mod list; pub(crate) mod read; +mod read_links; pub(crate) mod send; mod types; diff --git a/src/mail/read.rs b/src/mail/read.rs index 7c366e154..84dad1aad 100644 --- a/src/mail/read.rs +++ b/src/mail/read.rs @@ -82,7 +82,7 @@ fn safe_body(value: &Value) -> Result { Ok(json!({"text":text,"source":source,"bodyDirection":direction})) } -fn safe_render(value: &Value) -> Result { +fn safe_render(value: &Value) -> Result<(Value, Vec), &'static str> { let render = value.as_object().ok_or("mail_read_invalid_reader")?; if render.contains_key("html") || render @@ -96,7 +96,12 @@ fn safe_render(value: &Value) -> Result { .get("document") .filter(|document| document.is_object()) .ok_or("mail_read_invalid_reader")?; - fn document_node(value: &Value, depth: usize, left: &mut usize) -> Result { + fn document_node( + value: &Value, + depth: usize, + left: &mut usize, + links: &mut Vec, + ) -> Result { if depth > MAX_DEPTH || *left == 0 { return Err("mail_read_invalid_reader"); } @@ -120,7 +125,7 @@ fn safe_render(value: &Value) -> Result { .and_then(Value::as_array) .ok_or("mail_read_invalid_reader")? .iter() - .map(|child| document_node(child, depth + 1, left)) + .map(|child| document_node(child, depth + 1, left, links)) .collect::, _>>()?; if kind == "root" { return Ok(json!({"type":"root","children":children})); @@ -132,6 +137,11 @@ fn safe_render(value: &Value) -> Result { !name.is_empty() && name.len() <= 128 && !name.chars().any(char::is_control) }) .ok_or("mail_read_invalid_reader")?; + if name == "a" + && let Some(link) = super::read_links::link(value, &children) + { + links.push(link); + } Ok(json!({ "type":"element", "name":name, @@ -141,7 +151,9 @@ fn safe_render(value: &Value) -> Result { })) } let mut nodes_left = MAX_NODES; - Ok(json!({"document":document_node(document, 0, &mut nodes_left)?})) + let mut links = Vec::new(); + let document = document_node(document, 0, &mut nodes_left, &mut links)?; + Ok((json!({"document":document}), links)) } fn safe_message(request: &ReadRequest, value: Value) -> Result<(Value, Vec), &'static str> { @@ -190,7 +202,8 @@ fn safe_message(request: &ReadRequest, value: Value) -> Result<(Value, Vec Result<(Value, Vec String { + static ENTITIES: std::sync::LazyLock = std::sync::LazyLock::new(|| { + regex::Regex::new(r"&(?:#[0-9]+|#[xX][0-9a-fA-F]+|[a-zA-Z]+);?").unwrap() + }); + ENTITIES + .replace_all(value, |capture: ®ex::Captures| { + let entity = capture.get(0).unwrap(); + // In attributes, an unterminated named reference before '=' or an + // alphanumeric is literal URL data (for example ?a=1©=2). + if !entity.as_str().ends_with(';') + && !entity.as_str().starts_with("&#") + && value[entity.end()..] + .chars() + .next() + .is_some_and(|c| c == '=' || c.is_ascii_alphanumeric()) + { + entity.as_str().to_owned() + } else { + crate::message::html::decode_entities(entity.as_str()) + } + }) + .into_owned() +} + +pub(super) fn destination(value: &str) -> Option<&str> { + if value.len() > 8192 + || value.contains('\\') + || value.chars().any(|c| c.is_control() || c.is_whitespace()) + { + return None; + } + let url = reqwest::Url::parse(value).ok()?; + match url.scheme() { + "http" | "https" + if url.username().is_empty() + && url.password().is_none() + && crate::message::html::is_public_url(value) + && crate::message::html::is_public_url(url.as_str()) => + { + Some(value) + } + "mailto" if !url.path().is_empty() => Some(value), + _ => None, + } +} + +pub(super) fn link(node: &Value, children: &[Value]) -> Option { + let attrs = node["attrs"].as_array()?; + let href = attrs.iter().find(|attr| attr["name"] == "href")?["value"].as_str()?; + // Document attributes retain HTML entities for serialization. Decode once + // before checking and exporting the exact destination a caller will use. + let href = attribute_value(href); + let href = destination(&href)?; + fn text(node: &Value, out: &mut String) { + // Malformed nested anchors have their own entry. Do not duplicate + // their labels at every ancestor and amplify a bounded document. + if node["name"] == "a" { + return; + } + if node["type"] == "text" { + out.push_str(node["text"].as_str().unwrap_or("")); + } else if let Some(children) = node["children"].as_array() { + for child in children { + text(child, out); + } + } + } + let mut label = String::new(); + for child in children { + text(child, &mut label); + } + Some(json!({"text":crate::message::html::decode_entities(&label),"url":href})) +} + +pub(super) fn unsubscribe(headers: &Value) -> Value { + let mut urls = Vec::new(); + let mut seen = HashSet::new(); + let mut one_click = false; + if let Some(headers) = headers.as_array() { + for header in headers { + let name = header["name"].as_str().unwrap_or(""); + let value = header["value"].as_str().unwrap_or(""); + if name.eq_ignore_ascii_case("list-unsubscribe") { + // RFC 2369 destinations are angle-bracket delimited. Do not + // infer URLs from comments or reinterpret HTML entities here. + for part in value.split('<').skip(1) { + if let Some((url, _)) = part.split_once('>') + && let Some(url) = destination(url) + && seen.insert(url) + { + urls.push(url.to_owned()); + } + } + } else if name.eq_ignore_ascii_case("list-unsubscribe-post") { + one_click |= value + .trim() + .eq_ignore_ascii_case("List-Unsubscribe=One-Click"); + } + } + } + // This reports the sender's declaration, not authentication or permission + // to POST. RFC 8058 applies only to HTTPS destinations. + let one_click = one_click + && urls + .iter() + .any(|url| url.to_ascii_lowercase().starts_with("https:")); + json!({"urls":urls,"oneClick":one_click}) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn destinations_are_data_only_and_reject_unsafe_schemes_hosts_and_controls() { + for url in [ + "javascript:alert(1)", + "data:text/html,hello", + "file:///etc/passwd", + "/relative", + "//example.org/path", + "https:example.org/path", + "https:////example.org/path", + "https://localhost/path", + "http://127.0.0.1/path", + "http://2130706433/path", + "http://[::1]/path", + "https://private.local/path", + "https://user:secret@example.org/path", + "https://example.org/\r\ninjected", + "https://example.org/\n", + "https://example.org/\0", + "https://example.org/\\evil", + "mailto:", + ] { + assert_eq!(destination(url), None, "{url:?}"); + } + for url in [ + "https://example.org/工?a=1&b=%22quoted%22", + "mailto:leave@example.org?subject=unsubscribe", + ] { + assert_eq!(destination(url), Some(url)); + } + } + + #[test] + fn nested_anchor_labels_are_not_amplified() { + let node = json!({"attrs":[{"name":"href","value":"https://example.org/"}]}); + let children = vec![ + json!({"type":"text","text":"outer"}), + json!({"type":"element","name":"a","children":[{"type":"text","text":"inner"}]}), + ]; + assert_eq!(link(&node, &children).unwrap()["text"], "outer"); + } + + #[test] + fn html_entities_are_decoded_once_before_destination_validation() { + assert_eq!( + attribute_value("https://example.org/?a=1©=2®123=3"), + "https://example.org/?a=1©=2®123=3" + ); + let children = vec![json!({"type":"text","text":"Leave & goodbye"})]; + let node = |href: &str| json!({"attrs":[{"name":"href","value":href}]}); + assert_eq!( + link(&node("https://example.org/?a=1&b=&amp;"), &children), + Some(json!({"text":"Leave & goodbye","url":"https://example.org/?a=1&b=&"})) + ); + for href in [ + "javascript:bad", + "https://example.org/ ", + "http://127.0.0.1/", + "file:///etc/passwd", + ] { + assert_eq!(link(&node(href), &children), None, "{href}"); + } + // Headers are not HTML: an ampersand/entity spelling is URL data. + assert_eq!( + unsubscribe( + &json!([{"name":"List-Unsubscribe","value":""}]) + )["urls"], + json!(["https://example.org/?a=1&b=2"]) + ); + } + + #[test] + fn unsubscribe_is_allowlisted_deduplicated_and_requires_https_for_one_click() { + let headers = json!([ + {"name":"List-Unsubscribe","value":"comment https://ignored.example.org , , , "}, + {"name":"List-Unsubscribe-Post","value":"List-Unsubscribe=One-Click"} + ]); + assert_eq!( + unsubscribe(&headers), + json!({"urls":["mailto:leave@example.org"],"oneClick":false}) + ); + assert_eq!( + unsubscribe(&Value::Null), + json!({"urls":[],"oneClick":false}) + ); + } +} diff --git a/src/mail/read_tests.rs b/src/mail/read_tests.rs index ec9d39626..92ad84ace 100644 --- a/src/mail/read_tests.rs +++ b/src/mail/read_tests.rs @@ -93,6 +93,11 @@ async fn read_returns_only_safe_reader_content_without_conversation_metadata() { assert!(!result.to_string().contains("internal-reader-key")); assert!(result["message"]["attachments"][0]["data"].is_null()); assert_eq!(result["conversation"], json!([])); + assert_eq!(result["message"]["links"], json!([])); + assert_eq!( + result["message"]["unsubscribe"], + json!({"urls":[],"oneClick":false}) + ); let calls = calls.lock().unwrap(); assert_eq!(calls.len(), 1); @@ -112,6 +117,62 @@ async fn read_returns_only_safe_reader_content_without_conversation_metadata() { ); } +#[tokio::test] +async fn read_exposes_links_and_unsubscribe_metadata_without_fetching_destinations() { + for provider in [ + Provider::Gmail, + Provider::Outlook, + Provider::Imap, + Provider::Jmap, + Provider::Hey, + ] { + let mut response = cached_mime_reader_fixture(); + response["payload"]["headers"] = json!([ + {"name":"lIsT-UnSuBsCrIbE", "value":", "}, + {"name":"List-Unsubscribe-Post", "value":"List-Unsubscribe=One-Click"}, + {"name":"X-Private", "value":"not-exported"} + ]); + response["nativeRender"]["document"]["children"] = json!([ + {"type":"element","name":"a","attrs":[{"name":"href","value":"https://news.example.org/leave?a=1&b=2"},{"name":"onclick","value":"not-exported"}],"children":[ + {"type":"text","text":"Leave "}, + {"type":"element","name":"b","children":[{"type":"text","text":"工 newsletter"}]} + ]}, + {"type":"element","name":"img","attrs":[{"name":"src","value":"https://tracker.example/pixel"}],"children":[]} + ]); + let calls = Arc::new(Mutex::new(Vec::new())); + let mut request = request(); + request.account.provider = provider; + let result = read_with( + request, + &RecordingAdapter { + open_response: response, + conversation_response: json!({}), + calls: calls.clone(), + }, + ) + .await + .unwrap(); + assert_eq!( + result["message"]["links"], + json!([{"text":"Leave 工 newsletter","url":"https://news.example.org/leave?a=1&b=2"}]) + ); + assert_eq!( + result["message"]["unsubscribe"], + json!({"urls":["https://news.example.org/leave?a=1&b=2","mailto:leave@example.org?subject=unsubscribe"],"oneClick":true}) + ); + assert!(!result.to_string().contains("not-exported")); + assert!(!result.to_string().contains("tracker.example")); + assert_eq!( + result["message"]["nativeRender"]["document"]["children"][0]["attrs"], + json!([]) + ); + let calls = calls.lock().unwrap(); + assert_eq!(calls.len(), 1); + assert_eq!(calls[0].0, "reader.open"); + assert_eq!(calls[0].1["options"]["allowRemoteImages"], false); + } +} + #[tokio::test] async fn read_rejects_a_reader_response_for_another_message() { let mut response = cached_mime_reader_fixture(); diff --git a/src/message/html/mod.rs b/src/message/html/mod.rs index 927b7f4c0..708c82795 100644 --- a/src/message/html/mod.rs +++ b/src/message/html/mod.rs @@ -14,6 +14,7 @@ mod reader; #[cfg(test)] mod tests; mod tree; +pub(crate) use policy::decode as decode_entities; pub use policy::is_public_url; use policy::*; use serde_json::{Value, json}; diff --git a/tests/cli.rs b/tests/cli.rs index 54058c206..944a9297b 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -1678,7 +1678,16 @@ async fn root_list_and_read_use_active_account_and_safe_provider_results() { } else if line.starts_with("O1 UID FETCH 7 (UID FLAGS ") { assert!(line.contains("BODY.PEEK[")); assert_eq!(line.contains("BODY.PEEK[]"), read); - let raw = "From: Writer \r\nSubject: Safe root result\r\nContent-Type: text/plain; charset=utf-8\r\n\r\nsafe body 工"; + let raw = concat!( + "From: Writer \r\nSubject: Safe root result\r\n", + "List-Unsubscribe: ,\r\n \r\n", + "List-Unsubscribe-Post: List-Unsubscribe=One-Click\r\n", + "Content-Type: multipart/alternative; boundary=parts\r\n\r\n", + "--parts\r\nContent-Type: text/plain; charset=utf-8\r\n\r\nsafe body 工\r\n", + "--parts\r\nContent-Type: text/html; charset=utf-8\r\n\r\n", + "

safe body 工

Unsubscribe", + "Bad\r\n--parts--\r\n" + ); format!( "* 7 FETCH (UID 7 FLAGS () INTERNALDATE \"11-Sep-2026 12:00:00 +0000\" RFC822.SIZE {} BODY[] {{{}}}\r\n{}\r\n)\r\nO1 OK fetched\r\n", raw.len(), @@ -1718,6 +1727,20 @@ async fn root_list_and_read_use_active_account_and_safe_provider_results() { value["result"]["message"]["nativeContent"]["body"]["text"], "safe body 工" ); + assert_eq!( + value["result"]["message"]["links"], + serde_json::json!([ + {"text":"Unsubscribe","url":"https://news.example.org/leave?a=1&b=2"} + ]) + ); + assert_eq!( + value["result"]["message"]["unsubscribe"], + serde_json::json!({ + "urls":["https://news.example.org/leave","mailto:leave@example.org"],"oneClick":true + }) + ); + assert!(!value.to_string().contains("tracker.example")); + assert!(!value.to_string().contains("javascript:")); } else { assert_eq!(value["result"]["messages"][0]["id"], "7:INBOX"); assert_eq!(value["result"]["mailbox"], "inbox");