Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions docs/BACKEND.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
1 change: 1 addition & 0 deletions src/mail/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
27 changes: 21 additions & 6 deletions src/mail/read.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ fn safe_body(value: &Value) -> Result<Value, &'static str> {
Ok(json!({"text":text,"source":source,"bodyDirection":direction}))
}

fn safe_render(value: &Value) -> Result<Value, &'static str> {
fn safe_render(value: &Value) -> Result<(Value, Vec<Value>), &'static str> {
let render = value.as_object().ok_or("mail_read_invalid_reader")?;
if render.contains_key("html")
|| render
Expand All @@ -96,7 +96,12 @@ fn safe_render(value: &Value) -> Result<Value, &'static str> {
.get("document")
.filter(|document| document.is_object())
.ok_or("mail_read_invalid_reader")?;
fn document_node(value: &Value, depth: usize, left: &mut usize) -> Result<Value, &'static str> {
fn document_node(
value: &Value,
depth: usize,
left: &mut usize,
links: &mut Vec<Value>,
) -> Result<Value, &'static str> {
if depth > MAX_DEPTH || *left == 0 {
return Err("mail_read_invalid_reader");
}
Expand All @@ -120,7 +125,7 @@ fn safe_render(value: &Value) -> Result<Value, &'static str> {
.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::<Result<Vec<_>, _>>()?;
if kind == "root" {
return Ok(json!({"type":"root","children":children}));
Expand All @@ -132,6 +137,11 @@ fn safe_render(value: &Value) -> Result<Value, &'static str> {
!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,
Expand All @@ -141,7 +151,9 @@ fn safe_render(value: &Value) -> Result<Value, &'static str> {
}))
}
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<String>), &'static str> {
Expand Down Expand Up @@ -190,7 +202,8 @@ fn safe_message(request: &ReadRequest, value: Value) -> Result<(Value, Vec<Strin
})
.transpose()?
.unwrap_or_default();
let render = safe_render(&value["nativeRender"])?;
let (render, links) = safe_render(&value["nativeRender"])?;
let unsubscribe = super::read_links::unsubscribe(&value["payload"]["headers"]);
let content = json!({"body":body,"attachments":attachments});
Ok((
json!({
Expand All @@ -199,6 +212,8 @@ fn safe_message(request: &ReadRequest, value: Value) -> Result<(Value, Vec<Strin
"nativeContent":content,
"nativeRender":render,
"attachments":content["attachments"],
"links":links,
"unsubscribe":unsubscribe,
}),
members,
))
Expand Down Expand Up @@ -287,7 +302,7 @@ mod tests {
#[test]
fn safe_render_matches_the_native_document_node_limit() {
let at_limit = json!({"document":{"type":"root","children":leaf_nodes(MAX_NODES - 1)}});
let projected = safe_render(&at_limit).unwrap();
let (projected, _) = safe_render(&at_limit).unwrap();
assert_eq!(
projected["document"]["children"].as_array().unwrap().len(),
MAX_NODES - 1
Expand Down
204 changes: 204 additions & 0 deletions src/mail/read_links.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,204 @@
//! Data-only link projection. Never resolve, open or fetch sender destinations.
use serde_json::{Value, json};
use std::collections::HashSet;

fn attribute_value(value: &str) -> String {
static ENTITIES: std::sync::LazyLock<regex::Regex> = std::sync::LazyLock::new(|| {
regex::Regex::new(r"&(?:#[0-9]+|#[xX][0-9a-fA-F]+|[a-zA-Z]+);?").unwrap()
});
ENTITIES
.replace_all(value, |capture: &regex::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&copy=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<Value> {
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&copy=2&reg123=3"),
"https://example.org/?a=1&copy=2&reg123=3"
);
let children = vec![json!({"type":"text","text":"Leave &amp; goodbye"})];
let node = |href: &str| json!({"attrs":[{"name":"href","value":href}]});
assert_eq!(
link(&node("https://example.org/?a=1&amp;b=&amp;amp;"), &children),
Some(json!({"text":"Leave & goodbye","url":"https://example.org/?a=1&b=&amp;"}))
);
for href in [
"javascript&#58;bad",
"https://example.org/&#10;",
"http://127&#46;0.0.1/",
"file&#58;///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":"<https://example.org/?a=1&amp;b=2>"}])
)["urls"],
json!(["https://example.org/?a=1&amp;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 <javascript:bad>, <http://127.0.0.1/>, <mailto:leave@example.org>, <mailto:leave@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})
);
}
}
61 changes: 61 additions & 0 deletions src/mail/read_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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":"<https://news.example.org/leave?a=1&b=2>, <mailto:leave@example.org?subject=unsubscribe>"},
{"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();
Expand Down
Loading
Loading