Skip to main content

vector_core/transfer/
avatar.rs

1//! The sender's avatar for the new device's screen: a small thumbnail that rides in the sealed hello,
2//! so the new device fetches nothing before sign-in. The receiver re-encodes whatever arrives, so the
3//! page only ever renders a PNG this code produced.
4
5use std::io::Cursor;
6
7use image::imageops::FilterType;
8use image::{DynamicImage, ImageFormat, ImageReader, Limits, Rgba, RgbaImage};
9
10/// Thumbnail edge, in pixels: crisp at the card's 44 px on a 3x screen.
11const SIDE: u32 = 128;
12/// The largest thumbnail a sender includes or a receiver accepts.
13pub const MAX_BYTES: usize = 16 * 1024;
14/// What transparent corners settle on: the identity card's surface.
15const BACKDROP: Rgba<u8> = Rgba([22, 23, 24, 255]);
16
17/// A small square JPEG of the cached avatar `bytes`, or `None` if it won't decode or shrink enough.
18pub fn thumbnail(bytes: &[u8]) -> Option<Vec<u8>> {
19    let mut reader = ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?;
20    let mut limits = Limits::default();
21    limits.max_image_width = Some(4096);
22    limits.max_image_height = Some(4096);
23    limits.max_alloc = Some(64 * 1024 * 1024);
24    reader.limits(limits);
25    let img = reader.decode().ok()?;
26    let square = img.resize_to_fill(SIDE, SIDE, FilterType::Lanczos3).to_rgba8();
27    let mut flat = RgbaImage::from_pixel(SIDE, SIDE, BACKDROP);
28    image::imageops::overlay(&mut flat, &square, 0, 0);
29    let rgb = DynamicImage::ImageRgba8(flat).to_rgb8();
30    for quality in [88u8, 78, 65] {
31        let mut out = Vec::new();
32        image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, quality).encode_image(&rgb).ok()?;
33        if out.len() <= MAX_BYTES {
34            return Some(out);
35        }
36    }
37    None
38}
39
40/// A PNG data URL re-encoded from untrusted thumbnail `bytes`: raster formats only, small
41/// dimensions only, never handed to the page as received.
42pub fn sanitize(bytes: &[u8]) -> Option<String> {
43    if bytes.len() > MAX_BYTES {
44        return None;
45    }
46    let mut reader = ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?;
47    if !matches!(reader.format(), Some(ImageFormat::Jpeg | ImageFormat::Png | ImageFormat::WebP)) {
48        return None;
49    }
50    let mut limits = Limits::default();
51    limits.max_image_width = Some(512);
52    limits.max_image_height = Some(512);
53    limits.max_alloc = Some(4 * 1024 * 1024);
54    reader.limits(limits);
55    let img = reader.decode().ok()?;
56    let side = SIDE.min(img.width()).min(img.height()).max(1);
57    let square = img.resize_to_fill(side, side, FilterType::Lanczos3);
58    let mut png = Vec::new();
59    square.write_to(&mut Cursor::new(&mut png), ImageFormat::Png).ok()?;
60    Some(format!("data:image/png;base64,{}", crate::simd::base64::STANDARD.encode_to_string(&png)))
61}
62
63#[cfg(test)]
64mod tests {
65    use super::*;
66
67    fn png(width: u32, height: u32, alpha: u8) -> Vec<u8> {
68        let img = RgbaImage::from_fn(width, height, |x, y| Rgba([(x % 256) as u8, (y % 256) as u8, 200, alpha]));
69        let mut out = Vec::new();
70        DynamicImage::ImageRgba8(img).write_to(&mut Cursor::new(&mut out), ImageFormat::Png).unwrap();
71        out
72    }
73
74    #[test]
75    fn a_large_avatar_becomes_a_small_square_jpeg() {
76        let thumb = thumbnail(&png(1200, 800, 128)).unwrap();
77        assert!(thumb.len() <= MAX_BYTES);
78        assert_eq!(image::guess_format(&thumb).unwrap(), ImageFormat::Jpeg);
79        let back = image::load_from_memory(&thumb).unwrap();
80        assert_eq!((back.width(), back.height()), (SIDE, SIDE));
81        assert!(thumbnail(b"not an image").is_none());
82        assert!(thumbnail(&png(5000, 10, 255)).is_none(), "a source past the decode limits");
83    }
84
85    #[test]
86    fn only_a_small_raster_reaches_the_page_and_always_as_png() {
87        let url = sanitize(&thumbnail(&png(300, 300, 255)).unwrap()).unwrap();
88        let body = url.strip_prefix("data:image/png;base64,").expect("png data url");
89        let bytes = crate::simd::base64::STANDARD.decode_to_vec(body).unwrap();
90        assert_eq!(image::guess_format(&bytes).unwrap(), ImageFormat::Png);
91
92        let svg = br#"<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>"#;
93        assert!(sanitize(svg).is_none(), "never svg");
94        assert!(sanitize(b"<html>").is_none());
95        assert!(sanitize(&png(2000, 40, 255)).is_none(), "dimensions past the limit");
96        assert!(sanitize(&vec![0u8; MAX_BYTES + 1]).is_none(), "size past the limit");
97    }
98}