caprs 0.1.1

Image-based click, slide, drag and rotate CAPTCHA generation and verification
Documentation
//! Generate a circular image puzzle that the user rotates to match a reference.

use std::ops::RangeInclusive;

use image::RgbaImage;
use image::imageops;
use rand::seq::IndexedRandom;

use crate::{CaptchaError, Challenge, Format, Image, Size, render};

const FULL_TURN: i64 = 360;

/// Image sizes, angle ranges and transparency for a rotation CAPTCHA.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct Options {
    /// Side of the square canvas holding the unrotated reference image.
    pub image_size: u32,
    /// Inclusive ranges of clockwise angles applied to the thumbnail.
    pub angles: Vec<RangeInclusive<i16>>,
    /// Candidate sides of the square canvas holding the circular thumbnail.
    pub thumbnail_sizes: Vec<u32>,
    /// Opacity multiplier applied to the thumbnail.
    pub thumbnail_opacity: u8,
}

impl Default for Options {
    fn default() -> Self {
        Self {
            image_size: 220,
            angles: vec![RangeInclusive::new(30, 330)],
            thumbnail_sizes: vec![140, 150, 160, 170],
            thumbnail_opacity: 255,
        }
    }
}

/// Verification data for a rotated thumbnail.
#[derive(Clone, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Answer {
    angle: i16,
}

impl Answer {
    /// Returns the clockwise angle applied to the thumbnail during generation.
    #[must_use]
    pub fn angle(&self) -> i16 {
        self.angle
    }

    /// Checks the user's clockwise adjustment against the angle applied during generation.
    ///
    /// If the thumbnail was turned 90°, a clockwise adjustment of 270° solves it.
    #[must_use]
    pub fn verify(&self, clockwise_adjustment: i32, padding: u32) -> bool {
        validate(clockwise_adjustment, i32::from(self.angle), padding)
    }
}

/// Checks that the angle and adjustment sum to within padding of one full turn.
///
/// Inputs are expressed in degrees. The supplied values are compared without reducing
/// them modulo 360, preserving the upstream convention.
#[must_use]
pub fn validate(clockwise_adjustment: i32, angle: i32, padding: u32) -> bool {
    (i64::from(clockwise_adjustment) + i64::from(angle) - FULL_TURN).abs() <= i64::from(padding)
}

/// A reusable generator for circular rotation CAPTCHAs.
#[derive(Debug)]
pub struct Captcha {
    options: Options,
    backgrounds: Vec<RgbaImage>,
}

impl Captcha {
    /// Validates the requested sizes, angles, and full background images.
    ///
    /// # Errors
    ///
    /// Returns an error if the images, sizes, or angle ranges are missing or incompatible.
    pub fn new(options: Options, backgrounds: Vec<RgbaImage>) -> Result<Self, CaptchaError> {
        render::check_size(Size::square(options.image_size), "image_size")?;
        render::check_angles(&options.angles, 0..=360)?;
        if options.angles.is_empty() {
            return Err(CaptchaError::invalid(
                "angles",
                "at least one angle range is required",
            ));
        }
        if options.thumbnail_sizes.is_empty()
            || !options
                .thumbnail_sizes
                .iter()
                .all(|side| (1..=options.image_size).contains(side))
        {
            return Err(CaptchaError::invalid(
                "thumbnail_sizes",
                "need at least one positive thumbnail size no larger than the master image",
            ));
        }
        if backgrounds.is_empty() {
            return Err(CaptchaError::invalid(
                "rotate backgrounds",
                "at least one background is required",
            ));
        }
        for source in &backgrounds {
            render::check_image(source, "rotate background")?;
        }
        Ok(Self {
            options,
            backgrounds,
        })
    }

    /// Returns the options used by this generator.
    #[must_use]
    pub fn options(&self) -> &Options {
        &self.options
    }

    /// Draws the unrotated reference and a rotated center crop as transparent PNGs.
    ///
    /// # Errors
    ///
    /// Returns an error if the operating system cannot supply randomness.
    pub fn generate(&self) -> Result<Challenge<Answer>, CaptchaError> {
        let mut rng = crate::rng()?;
        let options = &self.options;
        let &side = options
            .thumbnail_sizes
            .choose(&mut rng)
            .expect("validated thumbnail sizes");
        let source = self
            .backgrounds
            .choose(&mut rng)
            .expect("validated rotation backgrounds");
        let angle = render::angle(&options.angles, &mut rng);
        let mut master =
            render::crop_background(source, Size::square(options.image_size), &mut rng);

        // The matching image content comes from the center of the same background crop.
        let inset = (options.image_size - side) / 2;
        let center = imageops::crop_imm(&master, inset, inset, side, side).to_image();
        let mut thumbnail = render::rotate(center, angle, Size::square(side));
        render::circle(&mut master);
        render::circle(&mut thumbnail);
        render::opacity(&mut thumbnail, options.thumbnail_opacity);

        Ok(Challenge::new(
            Image::new(master, Format::Png),
            Image::new(thumbnail, Format::Png),
            Answer { angle },
        ))
    }
}