[core] Sanitiser: Colours::Dark for the dark reader (backgrounds out, colours lifted to 4.5 : 1, rule borders, theme links, colours_changed)

This commit is contained in:
2026-11-22 21:24:54 +01:00
parent f65c959bb4
commit 15c1d0e7c2
9 changed files with 585 additions and 22 deletions
+2 -1
View File
@@ -13,7 +13,8 @@ src/compose.rs compose (mail-builder): multipart/alternative, attachments, re
src/filename.rs hostile attachment names -> safe names (../, reserved Windows names, bidi controls)
src/thread.rs threading: Message-ID / In-Reply-To / References, normalised-subject fallback
src/rules.rs incoming rules (from/to/subject contains -> move to folder), first match wins; Sieve export
src/sanitize.rs HTML sanitiser (ammonia allow-list), remote images -> placeholders
src/sanitize.rs HTML sanitiser (ammonia allow-list), remote images -> placeholders, the dark reader's colours
src/sanitize/colour.rs CSS colours: parse, WCAG contrast, grey, lighten in hue to 4.5 : 1
src/search.rs search query parser (free text, from:, to:, subject:, has:attachment, is:starred) -> FTS5
tests/ the mandatory tests (fixtures are built in code; no corpora in git)
```
Generated
+1 -1
View File
@@ -184,7 +184,7 @@ dependencies = [
[[package]]
name = "epistula-core"
version = "0.1.0"
version = "0.2.0"
dependencies = [
"ammonia",
"base64",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "epistula-core"
version = "0.1.0"
version = "0.2.0"
edition = "2024"
rust-version = "1.85"
license = "MPL-2.0"
+3 -1
View File
@@ -176,7 +176,9 @@ fn original_html(original: &Parsed) -> String {
})
.collect();
match &original.html {
Some(html) => sanitize(html, &SanitizeOptions { load_remote_images: false, inline_images }).html,
Some(html) => {
sanitize(html, &SanitizeOptions { load_remote_images: false, inline_images, ..Default::default() }).html
}
None => text_to_html(original.text.as_deref().unwrap_or("")),
}
}
+1 -1
View File
@@ -53,6 +53,6 @@ pub use compose::{Draft, OutAttachment, ReplyMode, compose, forward, message_id,
pub use filename::safe_filename;
pub use mime::{Attachment, ParseError, Parsed, parse};
pub use rules::{Condition, Field, Rule, RuleMessage, first_match, to_sieve};
pub use sanitize::{SanitizeOptions, Sanitized, sanitize, text_to_html};
pub use sanitize::{Colours, DarkPalette, SanitizeOptions, Sanitized, sanitize, text_to_html};
pub use search::{Query, parse_query};
pub use thread::{ThreadInput, normalize_subject, thread};
+168 -9
View File
@@ -5,12 +5,24 @@
//! Defence in depth after ammonia: in text and attribute values `:` and `=` are written as `:` and `=`.
//! A browser shows and follows exactly the same thing, but the output can never contain the literal sequences
//! `javascript:` or ` onclick=`, whatever a later bug in a filter lets through.
//!
//! Colours: `Colours::Original` keeps the mail's own (sanitised as above). `Colours::Dark` writes it for a dark
//! reader: backgrounds removed (a highlight on a few words becomes the palette's tint), black, grey and white
//! text removed, other text colours lightened in their own hue to `MIN_CONTRAST` on the body, borders in the rule
//! colour, links with no colour, background or decoration of their own, `!important` removed. Images are never
//! touched. `Sanitized::colours_changed` says whether that changed the look (the reader then offers the original).
mod colour;
pub use colour::{
GREY_CHROMA, GREY_SATURATION, MIN_CONTRAST, Rgb, contrast, is_grey, luminance, parse_colour, readable_on,
};
use base64::Engine;
use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
/// What an inline `cid:` image resolves to.
pub struct InlineImage<'a> {
@@ -24,6 +36,46 @@ pub struct SanitizeOptions<'a> {
pub load_remote_images: bool,
/// Inline parts by Content-ID (no brackets): `cid:` sources become `data:` URIs.
pub inline_images: HashMap<String, InlineImage<'a>>,
/// The colours to write for: the mail's own (the default), or a dark reader's.
pub colours: Colours,
}
/// Which colours the output carries.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Colours {
/// The mail's own colours, as v0.1.0 wrote them (byte for byte).
#[default]
Original,
/// Rewritten for a dark body: see the module docs.
Dark(DarkPalette),
}
/// The reader's colours the dark output is written for. `body` must be dark: white reaches `MIN_CONTRAST` on it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DarkPalette {
/// The body's background: every kept text colour reaches `MIN_CONTRAST` on it.
pub body: Rgb,
/// Every border and rule.
pub rule: Rgb,
/// A highlight on a few words, drawn at `highlight_alpha_percent` over the body.
pub highlight: Rgb,
pub highlight_alpha_percent: u8,
}
impl DarkPalette {
/// Epistula's dark Domi theme: `--reader-bg` `#111726`, `--reader-rule` `#6b7a99`, the tint of `--second`.
pub const DOMI: Self = Self {
body: Rgb::new(0x11, 0x17, 0x26),
rule: Rgb::new(0x6b, 0x7a, 0x99),
highlight: Rgb::new(244, 201, 93),
highlight_alpha_percent: 13,
};
/// The highlight as a CSS value, e.g. `rgba(244, 201, 93, 0.13)`.
pub fn highlight_css(&self) -> String {
let h = self.highlight;
format!("rgba({}, {}, {}, {})", h.r, h.g, h.b, f64::from(self.highlight_alpha_percent.min(100)) / 100.0)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -31,11 +83,52 @@ pub struct Sanitized {
pub html: String,
/// Remote images replaced by the placeholder: show "Load images" only when this is not zero.
pub blocked_images: usize,
/// `Colours::Dark` changed the look: a background was removed or a colour lightened. Black, grey or white
/// text removed is no change (the body's white is what it meant). Always `false` for `Colours::Original`.
pub colours_changed: bool,
}
/// The placeholder for a blocked remote image (a small grey square, SVG in a data URI: no script runs in `<img>`).
pub const BLOCKED_IMAGE_SRC: &str = "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCI+PHJlY3Qgd2lkdGg9IjI0IiBoZWlnaHQ9IjI0IiBmaWxsPSIjNDQ0Ii8+PC9zdmc+";
/// The same placeholder in the dark (`#6b7a99`: `#444` is 1.9 : 1 on the dark body).
pub const BLOCKED_IMAGE_SRC_DARK: &str = "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCI+PHJlY3Qgd2lkdGg9IjI0IiBoZWlnaHQ9IjI0IiBmaWxsPSIjNmI3YTk5Ii8+PC9zdmc+";
/// Where a background is a highlight on a few words (it becomes the palette's tint), not a block's paint.
const HIGHLIGHT_TAGS: &[&str] = &["span", "font", "mark", "b", "i", "u", "strong", "em"];
/// Border shorthands: their colour words are replaced by the rule colour.
const BORDER_SHORTHANDS: &[&str] = &["border", "border-top", "border-right", "border-bottom", "border-left"];
/// The dark rewrite's state for one `sanitize` call.
struct Dark {
palette: DarkPalette,
changed: Arc<AtomicBool>,
}
impl Dark {
fn change(&self) {
self.changed.store(true, Ordering::Relaxed);
}
/// A text colour: `None` (removed) for grey or unreadable values, else readable on the body.
fn text_colour(&self, value: &str) -> Option<Rgb> {
let c = parse_colour(value).filter(|c| !is_grey(*c))?;
let out = readable_on(c, self.palette.body);
if out != c {
self.change();
}
Some(out)
}
/// A removed background: a change unless it named nothing (`none`, `transparent`, …).
fn removed_background(&self, value: &str) {
if !colour::names_nothing(value) {
self.change();
}
}
}
/// Inline images larger than this are not embedded (they stay attachments).
pub const MAX_INLINE_IMAGE_BYTES: usize = 10 * 1024 * 1024;
@@ -252,6 +345,11 @@ pub fn sanitize(html: &str, options: &SanitizeOptions<'_>) -> Sanitized {
.collect(),
);
let load_remote = options.load_remote_images;
let changed = Arc::new(AtomicBool::new(false));
let dark = match options.colours {
Colours::Original => None,
Colours::Dark(palette) => Some(Dark { palette, changed: changed.clone() }),
};
let mut builder = ammonia::Builder::empty();
builder
@@ -272,11 +370,15 @@ pub fn sanitize(html: &str, options: &SanitizeOptions<'_>) -> Sanitized {
{
let blocked = blocked.clone();
builder.attribute_filter(move |element, attribute, value| {
filter_attribute(element, attribute, value, load_remote, &inline, &blocked)
filter_attribute(element, attribute, value, load_remote, &inline, &blocked, dark.as_ref())
});
}
let cleaned = builder.clean(html).to_string();
Sanitized { html: escape_punctuation(&cleaned), blocked_images: blocked.load(Ordering::Relaxed) }
Sanitized {
html: escape_punctuation(&cleaned),
blocked_images: blocked.load(Ordering::Relaxed),
colours_changed: changed.load(Ordering::Relaxed),
}
}
/// The scheme of a URL as a browser would read it: ASCII whitespace and controls removed, lower case.
@@ -292,6 +394,7 @@ fn filter_attribute<'u>(
load_remote: bool,
inline: &HashMap<String, String>,
blocked: &AtomicUsize,
dark: Option<&Dark>,
) -> Option<Cow<'u, str>> {
match (element, attribute) {
("img", "src") => {
@@ -309,7 +412,7 @@ fn filter_attribute<'u>(
return Some(Cow::Borrowed(value));
}
blocked.fetch_add(1, Ordering::Relaxed);
return Some(Cow::Borrowed(BLOCKED_IMAGE_SRC));
return Some(Cow::Borrowed(if dark.is_some() { BLOCKED_IMAGE_SRC_DARK } else { BLOCKED_IMAGE_SRC }));
}
None
}
@@ -318,18 +421,32 @@ fn filter_attribute<'u>(
(url.starts_with("https:") || url.starts_with("http:") || url.starts_with("mailto:"))
.then_some(Cow::Borrowed(value))
}
(_, "style") => filter_css(value).map(Cow::Owned),
(_, "style") => filter_css(value, element, dark).map(Cow::Owned),
(_, "bgcolor") if dark.is_some() => {
if let Some(d) = dark {
d.removed_background(value);
}
None
}
("font", "color") if dark.is_some() => {
dark.and_then(|d| d.text_colour(value)).map(|c| Cow::Owned(c.to_string()))
}
_ => Some(Cow::Borrowed(value)),
}
}
/// Keeps only allow-listed properties whose values cannot run or load anything.
fn filter_css(style: &str) -> Option<String> {
/// Keeps only allow-listed properties whose values cannot run or load anything; in the dark, rewrites colours.
fn filter_css(style: &str, element: &str, dark: Option<&Dark>) -> Option<String> {
let mut kept = Vec::new();
let mut tinted = false;
for declaration in style.split(';') {
let Some((property, value)) = declaration.split_once(':') else { continue };
let property = property.trim().to_ascii_lowercase();
let value = value.trim();
let mut value = value.trim();
if dark.is_some() {
// `!important` (and anything else after a `!`) goes, so the reader's own rules always win.
value = value.split('!').next().unwrap_or("").trim_end();
}
let lower = value.to_ascii_lowercase();
if !CSS_PROPERTIES.contains(&property.as_str())
|| value.is_empty()
@@ -338,11 +455,53 @@ fn filter_css(style: &str) -> Option<String> {
{
continue;
}
kept.push(format!("{property}: {value}"));
match dark {
None => kept.push(format!("{property}: {value}")),
Some(d) => kept.extend(dark_declaration(&property, value, element, d, &mut tinted)),
}
}
(!kept.is_empty()).then(|| kept.join("; "))
}
/// A word of a CSS value that is a colour (`transparent` and `currentcolor` included).
fn is_colour_word(word: &str) -> bool {
parse_colour(word).is_some()
|| word.eq_ignore_ascii_case("transparent")
|| word.eq_ignore_ascii_case("currentcolor")
}
/// One allowed declaration, rewritten for the dark (`None`: removed).
fn dark_declaration(property: &str, value: &str, element: &str, dark: &Dark, tinted: &mut bool) -> Option<String> {
let rule = dark.palette.rule;
match property {
"background" | "background-color" => {
dark.removed_background(value);
let highlight = HIGHLIGHT_TAGS.contains(&element)
&& colour::words(value).iter().filter_map(|w| parse_colour(w)).any(|c| !is_grey(c));
if highlight && !*tinted {
*tinted = true;
return Some(format!("background-color: {}", dark.palette.highlight_css()));
}
None
}
// Links are the reader's: its colour, its underline.
"color" | "text-decoration" if element == "a" => None,
"color" => dark.text_colour(value).map(|c| format!("color: {c}")),
"text-decoration" => {
let rest: Vec<&str> = colour::words(value).into_iter().filter(|w| !is_colour_word(w)).collect();
(!rest.is_empty()).then(|| format!("{property}: {}", rest.join(" ")))
}
p if p.starts_with("border") && p.ends_with("-color") => Some(format!("{property}: {rule}")),
p if BORDER_SHORTHANDS.contains(&p) => {
let mut rest: Vec<String> =
colour::words(value).into_iter().filter(|w| !is_colour_word(w)).map(String::from).collect();
rest.push(rule.to_string());
Some(format!("{property}: {}", rest.join(" ")))
}
_ => Some(format!("{property}: {value}")),
}
}
/// Writes `:` and `=` in text and attribute values as character references (see the module docs).
/// The input is ammonia's serialisation: attribute values are always double-quoted and text never holds a raw `<`.
fn escape_punctuation(html: &str) -> String {
+399
View File
@@ -0,0 +1,399 @@
//! CSS colours as a mail writes them, and the arithmetic of the dark reader: WCAG contrast, "is this grey",
//! and lightening a colour in its own hue until it reads on the body.
//!
//! A mail's colour is hostile input like the rest of it: anything this parser does not know is `None`, and the
//! sanitiser then drops it.
use std::fmt;
/// An opaque sRGB colour. Written (`Display`) as `#rrggbb`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Rgb {
pub r: u8,
pub g: u8,
pub b: u8,
}
impl Rgb {
pub const fn new(r: u8, g: u8, b: u8) -> Self {
Self { r, g, b }
}
}
impl fmt::Display for Rgb {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "#{:02x}{:02x}{:02x}", self.r, self.g, self.b)
}
}
/// The contrast every text colour of a dark mail reaches on the body (WCAG AA for body text).
pub const MIN_CONTRAST: f64 = 4.5;
/// Under this HSL saturation a colour is a grey (black and white included): the sanitiser removes it.
pub const GREY_SATURATION: f64 = 0.10;
/// Under this chroma (the largest channel minus the smallest, of 255) a colour is a grey too: near-black and
/// near-white tints such as `#1b2130` or `#fff8f0` have a high HSL saturation but read as black and white.
pub const GREY_CHROMA: f64 = 0.10;
/// How far one step of lightening moves the HSL lightness.
const LIGHTEN_STEP: f64 = 0.01;
fn linear(channel: u8) -> f64 {
let s = f64::from(channel) / 255.0;
if s <= 0.04045 { s / 12.92 } else { ((s + 0.055) / 1.055).powf(2.4) }
}
/// WCAG relative luminance.
pub fn luminance(c: Rgb) -> f64 {
0.2126 * linear(c.r) + 0.7152 * linear(c.g) + 0.0722 * linear(c.b)
}
/// WCAG contrast ratio, 1 to 21.
pub fn contrast(a: Rgb, b: Rgb) -> f64 {
let (x, y) = (luminance(a), luminance(b));
(x.max(y) + 0.05) / (x.min(y) + 0.05)
}
/// Hue in degrees, saturation and lightness in 0..=1.
fn to_hsl(c: Rgb) -> (f64, f64, f64) {
let (r, g, b) = (f64::from(c.r) / 255.0, f64::from(c.g) / 255.0, f64::from(c.b) / 255.0);
let max = r.max(g).max(b);
let min = r.min(g).min(b);
let l = (max + min) / 2.0;
let d = max - min;
if d == 0.0 {
return (0.0, 0.0, l);
}
let s = d / (1.0 - (2.0 * l - 1.0).abs());
let h = if max == r {
60.0 * (((g - b) / d).rem_euclid(6.0))
} else if max == g {
60.0 * ((b - r) / d + 2.0)
} else {
60.0 * ((r - g) / d + 4.0)
};
(h, s.min(1.0), l)
}
fn from_hsl(h: f64, s: f64, l: f64) -> Rgb {
let c = (1.0 - (2.0 * l - 1.0).abs()) * s;
let hp = h.rem_euclid(360.0) / 60.0;
let x = c * (1.0 - (hp.rem_euclid(2.0) - 1.0).abs());
let (r, g, b) = match hp as u32 {
0 => (c, x, 0.0),
1 => (x, c, 0.0),
2 => (0.0, c, x),
3 => (0.0, x, c),
4 => (x, 0.0, c),
_ => (c, 0.0, x),
};
let m = l - c / 2.0;
let byte = |v: f64| ((v + m) * 255.0).round().clamp(0.0, 255.0) as u8;
Rgb::new(byte(r), byte(g), byte(b))
}
/// Black, grey or white: removed in the dark, so the text is the body's own.
pub fn is_grey(c: Rgb) -> bool {
let (_, s, _) = to_hsl(c);
let chroma = f64::from(c.r.max(c.g).max(c.b) - c.r.min(c.g).min(c.b)) / 255.0;
s < GREY_SATURATION || chroma < GREY_CHROMA
}
/// The colour itself if it reaches `MIN_CONTRAST` on `body`; else the same hue and saturation, lightened step by
/// step until it does. `body` must be dark (white reaches 4.5 : 1 on it), as the dark palette's is.
pub fn readable_on(c: Rgb, body: Rgb) -> Rgb {
if contrast(c, body) >= MIN_CONTRAST {
return c;
}
let (h, s, l) = to_hsl(c);
let mut step = 1.0;
loop {
let lightness = (l + LIGHTEN_STEP * step).min(1.0);
let out = from_hsl(h, s, lightness);
if contrast(out, body) >= MIN_CONTRAST || lightness >= 1.0 {
return out;
}
step += 1.0;
}
}
/// Values that name no colour at all: a background of these was not there to remove.
pub(super) fn names_nothing(value: &str) -> bool {
matches!(
value.trim().to_ascii_lowercase().as_str(),
"" | "none" | "transparent" | "inherit" | "initial" | "unset" | "revert" | "currentcolor" | "0"
)
}
/// The words of a CSS value, split on spaces outside parentheses (`1px solid rgb(1, 2, 3)` is three words).
pub(super) fn words(value: &str) -> Vec<&str> {
let mut out = Vec::new();
let mut depth = 0u32;
let mut start = None;
for (i, c) in value.char_indices() {
match c {
'(' => depth += 1,
')' => depth = depth.saturating_sub(1),
_ => {}
}
if c.is_ascii_whitespace() && depth == 0 {
if let Some(s) = start.take() {
out.push(&value[s..i]);
}
} else if start.is_none() {
start = Some(i);
}
}
if let Some(s) = start {
out.push(&value[s..]);
}
out
}
/// A CSS colour: `#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`, `rgb()`/`rgba()`, `hsl()`/`hsla()` (commas or spaces,
/// numbers or percentages) or a named colour. Alpha is ignored (text a mail makes transparent is shown).
/// `transparent`, `currentcolor` and anything else are `None`.
pub fn parse_colour(value: &str) -> Option<Rgb> {
let v = value.trim().to_ascii_lowercase();
if let Some(hex) = v.strip_prefix('#') {
return parse_hex(hex);
}
if let Some(args) = v.strip_prefix("rgba(").or_else(|| v.strip_prefix("rgb(")) {
let n = arguments(args)?;
let channel = |s: &str| -> Option<u8> {
let x = match s.strip_suffix('%') {
Some(p) => p.parse::<f64>().ok()? * 2.55,
None => s.parse::<f64>().ok()?,
};
x.is_finite().then(|| x.round().clamp(0.0, 255.0) as u8)
};
return Some(Rgb::new(channel(n[0])?, channel(n[1])?, channel(n[2])?));
}
if let Some(args) = v.strip_prefix("hsla(").or_else(|| v.strip_prefix("hsl(")) {
let n = arguments(args)?;
let h = n[0].strip_suffix("deg").unwrap_or(n[0]).parse::<f64>().ok()?;
let percent = |s: &str| -> Option<f64> {
s.strip_suffix('%').unwrap_or(s).parse::<f64>().ok().map(|p| (p / 100.0).clamp(0.0, 1.0))
};
let (s, l) = (percent(n[1])?, percent(n[2])?);
return h.is_finite().then(|| from_hsl(h, s, l));
}
NAMED.iter().find(|(name, _)| *name == v).map(|(_, hex)| Rgb::new((hex >> 16) as u8, (hex >> 8) as u8, *hex as u8))
}
/// The 3 or 4 arguments of `rgb(…)` / `hsl(…)`, up to the closing parenthesis, which must end the value.
fn arguments(args: &str) -> Option<Vec<&str>> {
let inner = args.strip_suffix(')')?;
let n: Vec<&str> = inner.split([',', ' ', '/']).filter(|s| !s.is_empty()).collect();
(n.len() == 3 || n.len() == 4).then_some(n)
}
fn parse_hex(hex: &str) -> Option<Rgb> {
if !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
return None;
}
let digit = |i: usize| u8::from_str_radix(&hex[i..i + 1], 16).ok();
let pair = |i: usize| u8::from_str_radix(&hex[i..i + 2], 16).ok();
match hex.len() {
3 | 4 => Some(Rgb::new(digit(0)? * 17, digit(1)? * 17, digit(2)? * 17)),
6 | 8 => Some(Rgb::new(pair(0)?, pair(2)?, pair(4)?)),
_ => None,
}
}
/// The CSS named colours (CSS Color 4), but `transparent`.
const NAMED: &[(&str, u32)] = &[
("aliceblue", 0xf0f8ff),
("antiquewhite", 0xfaebd7),
("aqua", 0x00ffff),
("aquamarine", 0x7fffd4),
("azure", 0xf0ffff),
("beige", 0xf5f5dc),
("bisque", 0xffe4c4),
("black", 0x000000),
("blanchedalmond", 0xffebcd),
("blue", 0x0000ff),
("blueviolet", 0x8a2be2),
("brown", 0xa52a2a),
("burlywood", 0xdeb887),
("cadetblue", 0x5f9ea0),
("chartreuse", 0x7fff00),
("chocolate", 0xd2691e),
("coral", 0xff7f50),
("cornflowerblue", 0x6495ed),
("cornsilk", 0xfff8dc),
("crimson", 0xdc143c),
("cyan", 0x00ffff),
("darkblue", 0x00008b),
("darkcyan", 0x008b8b),
("darkgoldenrod", 0xb8860b),
("darkgray", 0xa9a9a9),
("darkgreen", 0x006400),
("darkgrey", 0xa9a9a9),
("darkkhaki", 0xbdb76b),
("darkmagenta", 0x8b008b),
("darkolivegreen", 0x556b2f),
("darkorange", 0xff8c00),
("darkorchid", 0x9932cc),
("darkred", 0x8b0000),
("darksalmon", 0xe9967a),
("darkseagreen", 0x8fbc8f),
("darkslateblue", 0x483d8b),
("darkslategray", 0x2f4f4f),
("darkslategrey", 0x2f4f4f),
("darkturquoise", 0x00ced1),
("darkviolet", 0x9400d3),
("deeppink", 0xff1493),
("deepskyblue", 0x00bfff),
("dimgray", 0x696969),
("dimgrey", 0x696969),
("dodgerblue", 0x1e90ff),
("firebrick", 0xb22222),
("floralwhite", 0xfffaf0),
("forestgreen", 0x228b22),
("fuchsia", 0xff00ff),
("gainsboro", 0xdcdcdc),
("ghostwhite", 0xf8f8ff),
("gold", 0xffd700),
("goldenrod", 0xdaa520),
("gray", 0x808080),
("green", 0x008000),
("greenyellow", 0xadff2f),
("grey", 0x808080),
("honeydew", 0xf0fff0),
("hotpink", 0xff69b4),
("indianred", 0xcd5c5c),
("indigo", 0x4b0082),
("ivory", 0xfffff0),
("khaki", 0xf0e68c),
("lavender", 0xe6e6fa),
("lavenderblush", 0xfff0f5),
("lawngreen", 0x7cfc00),
("lemonchiffon", 0xfffacd),
("lightblue", 0xadd8e6),
("lightcoral", 0xf08080),
("lightcyan", 0xe0ffff),
("lightgoldenrodyellow", 0xfafad2),
("lightgray", 0xd3d3d3),
("lightgreen", 0x90ee90),
("lightgrey", 0xd3d3d3),
("lightpink", 0xffb6c1),
("lightsalmon", 0xffa07a),
("lightseagreen", 0x20b2aa),
("lightskyblue", 0x87cefa),
("lightslategray", 0x778899),
("lightslategrey", 0x778899),
("lightsteelblue", 0xb0c4de),
("lightyellow", 0xffffe0),
("lime", 0x00ff00),
("limegreen", 0x32cd32),
("linen", 0xfaf0e6),
("magenta", 0xff00ff),
("maroon", 0x800000),
("mediumaquamarine", 0x66cdaa),
("mediumblue", 0x0000cd),
("mediumorchid", 0xba55d3),
("mediumpurple", 0x9370db),
("mediumseagreen", 0x3cb371),
("mediumslateblue", 0x7b68ee),
("mediumspringgreen", 0x00fa9a),
("mediumturquoise", 0x48d1cc),
("mediumvioletred", 0xc71585),
("midnightblue", 0x191970),
("mintcream", 0xf5fffa),
("mistyrose", 0xffe4e1),
("moccasin", 0xffe4b5),
("navajowhite", 0xffdead),
("navy", 0x000080),
("oldlace", 0xfdf5e6),
("olive", 0x808000),
("olivedrab", 0x6b8e23),
("orange", 0xffa500),
("orangered", 0xff4500),
("orchid", 0xda70d6),
("palegoldenrod", 0xeee8aa),
("palegreen", 0x98fb98),
("paleturquoise", 0xafeeee),
("palevioletred", 0xdb7093),
("papayawhip", 0xffefd5),
("peachpuff", 0xffdab9),
("peru", 0xcd853f),
("pink", 0xffc0cb),
("plum", 0xdda0dd),
("powderblue", 0xb0e0e6),
("purple", 0x800080),
("rebeccapurple", 0x663399),
("red", 0xff0000),
("rosybrown", 0xbc8f8f),
("royalblue", 0x4169e1),
("saddlebrown", 0x8b4513),
("salmon", 0xfa8072),
("sandybrown", 0xf4a460),
("seagreen", 0x2e8b57),
("seashell", 0xfff5ee),
("sienna", 0xa0522d),
("silver", 0xc0c0c0),
("skyblue", 0x87ceeb),
("slateblue", 0x6a5acd),
("slategray", 0x708090),
("slategrey", 0x708090),
("snow", 0xfffafa),
("springgreen", 0x00ff7f),
("steelblue", 0x4682b4),
("tan", 0xd2b48c),
("teal", 0x008080),
("thistle", 0xd8bfd8),
("tomato", 0xff6347),
("turquoise", 0x40e0d0),
("violet", 0xee82ee),
("wheat", 0xf5deb3),
("white", 0xffffff),
("whitesmoke", 0xf5f5f5),
("yellow", 0xffff00),
("yellowgreen", 0x9acd32),
];
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hsl_round_trips_every_grey_and_primary() {
for c in [
Rgb::new(0, 0, 0),
Rgb::new(255, 255, 255),
Rgb::new(255, 0, 0),
Rgb::new(0, 128, 0),
Rgb::new(0x1a, 0x43, 0xa6),
] {
let (h, s, l) = to_hsl(c);
assert_eq!(from_hsl(h, s, l), c);
}
}
#[test]
fn words_keep_functions_whole() {
assert_eq!(words(" 1px solid rgb(1, 2, 3) "), ["1px", "solid", "rgb(1, 2, 3)"]);
assert_eq!(words(""), Vec::<&str>::new());
}
#[test]
fn hostile_colour_values_are_none_not_a_panic() {
for v in [
"#",
"#ééé",
"rgb(",
"rgb()",
"rgb(1e999, 0, 0)",
"rgb(nan, 0, 0)",
"hsl(inf, 1%, 1%)",
"rgb(1,2,3,4,5)",
"ĉ",
] {
let _ = parse_colour(v);
}
assert_eq!(parse_colour("rgb(1e999, 0, 0)"), None);
assert_eq!(parse_colour("hsl(inf, 1%, 1%)"), None);
assert_eq!(parse_colour("#ééé"), None);
assert_eq!(parse_colour(" RGB(255 0 0 / 50%) "), Some(Rgb::new(255, 0, 0)));
assert_eq!(parse_colour("#0f08"), Some(Rgb::new(0, 255, 0)));
}
}
+4 -2
View File
@@ -120,8 +120,10 @@ fn inline_cid_image_becomes_a_data_uri_in_the_reader() {
inline.content_id.clone().unwrap(),
InlineImage { content_type: &inline.content_type, data: &inline.data },
);
let out =
sanitize(m.html.as_deref().unwrap(), &SanitizeOptions { load_remote_images: false, inline_images: images });
let out = sanitize(
m.html.as_deref().unwrap(),
&SanitizeOptions { load_remote_images: false, inline_images: images, ..Default::default() },
);
assert!(out.html.contains("data&#58;image/png;base64,"), "{}", out.html);
assert!(!out.html.contains("cid"), "{}", out.html);
assert_eq!(out.blocked_images, 0);
+6 -6
View File
@@ -533,18 +533,16 @@ fn dark_rewrites_a_coloured_mail() {
#[test]
fn colours_are_lightened_in_their_hue_to_the_minimum_contrast() {
// The examples of the design: each lands within a few steps of the drawn colour.
// The examples of the design: exactly the drawn colours (HSL lightness raised in steps of 1 %).
for (from, drawn) in [("#c0392b", "#d7594c"), ("#2e7d32", "#36933b"), ("#1a43a6", "#517ce4")] {
let out = dark(&format!("<p style=\"color: {from}\">x</p>"));
assert!(out.colours_changed, "{from} was lightened");
let html = decoded(&out.html);
let value = first_colour(&html).unwrap_or_default();
let got = parse_colour(&value).unwrap_or_else(|| panic!("{from}: no colour in {html}"));
let want = parse_colour(drawn).unwrap();
assert!(contrast(got, PALETTE.body) >= MIN_CONTRAST, "{from} -> {got}");
assert!(contrast(got, PALETTE.body) < MIN_CONTRAST + 0.4, "{from} -> {got}: lightened more than needed");
let far = |a: u8, b: u8| a.abs_diff(b) > 8;
assert!(!(far(got.r, want.r) || far(got.g, want.g) || far(got.b, want.b)), "{from} -> {got}, drawn {drawn}");
assert_eq!(got.to_string(), drawn, "{from}");
}
// A colour that is already readable stays as it is, and is no change.
let light = dark("<p style=\"color: #8fd8b5\">x</p>");
@@ -571,7 +569,8 @@ fn black_grey_and_white_text_goes_and_is_no_change() {
"currentColor",
"hsl(0, 5%, 40%)",
] {
let out = dark(&format!("<p style=\"color: {colour}; font-size: 14px\">x</p><font color=\"{colour}\">y</font>"));
let out =
dark(&format!("<p style=\"color: {colour}; font-size: 14px\">x</p><font color=\"{colour}\">y</font>"));
let html = decoded(&out.html);
assert!(!html.contains("color"), "{colour}: {html}");
assert!(html.contains("font-size: 14px"), "{colour}: everything else stays ({html})");
@@ -605,7 +604,8 @@ fn a_highlight_on_words_becomes_the_tint_and_blocks_lose_theirs() {
}
for tag in ["div", "p", "td"] {
let html = decoded(
&dark(&format!("<table><tr><td><{tag} style=\"background-color: #ffeb3b\">x</{tag}></td></tr></table>")).html,
&dark(&format!("<table><tr><td><{tag} style=\"background-color: #ffeb3b\">x</{tag}></td></tr></table>"))
.html,
);
assert!(!html.contains("background"), "{tag}: {html}");
}