caprs 0.1.0

Image-based click, slide, drag and rotate CAPTCHA generation and verification
Documentation
//! Generate image-based CAPTCHA challenges and verify responses.
//!
//! Click CAPTCHAs use text or shapes. Slide and drag CAPTCHAs cut a piece from a
//! background, and rotate CAPTCHAs ask the user to realign a circular crop.
//! Keep the answer on the server and send the client only the images and any
//! display metadata it needs. Use the original image coordinates for verification.
//!
//! ```
//! use caprs::click;
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let captcha = click::Captcha::new(click::Options::default(), click::Symbols::bundled_text()?)?;
//! let (images, answer) = captcha.generate()?.into_parts();
//! let hint = images.prompt().to_data_url()?;
//! assert!(hint.starts_with("data:image/png;base64,"));
//! assert!(!answer.verify(&[], 0));
//! # Ok(())
//! # }
//! ```

pub mod click;
mod output;
mod render;
pub mod rotate;
pub mod slide;

pub use image;
pub use output::{Format, Image, ImageError};

use rand::SeedableRng;
use rand::rngs::StdRng;
use thiserror::Error;

/// A point in image pixels, measured from the top left with y increasing down.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Point {
    /// Horizontal coordinate.
    pub x: i32,
    /// Vertical coordinate.
    pub y: i32,
}

impl Point {
    /// Creates a point from its horizontal and vertical coordinates.
    #[must_use]
    pub const fn new(x: i32, y: i32) -> Self {
        Self { x, y }
    }
}

/// The width and height of an image or region in pixels.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Size {
    /// Horizontal extent in pixels.
    pub width: u32,
    /// Vertical extent in pixels.
    pub height: u32,
}

impl Size {
    /// Creates a size from its width and height.
    #[must_use]
    pub const fn new(width: u32, height: u32) -> Self {
        Self { width, height }
    }

    /// Creates a size with equal width and height.
    #[must_use]
    pub const fn square(side: u32) -> Self {
        Self::new(side, side)
    }
}

/// A rectangle described by an image-space corner and pixel dimensions.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Rect {
    /// The upper-left point.
    pub origin: Point,
    /// Horizontal and vertical extent.
    pub size: Size,
}

impl Rect {
    /// Creates a rectangle from its upper-left corner and dimensions.
    #[must_use]
    pub const fn new(origin: Point, size: Size) -> Self {
        Self { origin, size }
    }
}

/// An invalid CAPTCHA configuration or a failure to generate a challenge.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum CaptchaError {
    /// A setting or resource is incompatible with the generator.
    #[error("invalid {field}: {reason}")]
    Invalid {
        /// The name of the setting or resource.
        field: &'static str,
        /// The constraint that the value failed.
        reason: &'static str,
    },
    /// The operating system could not provide randomness.
    #[error("could not seed the challenge generator")]
    Random(#[from] rand::rand_core::OsError),
    /// A font mapped a label to glyphs without a renderable outline.
    #[error("no visible glyphs for click label {label:?}")]
    EmptyGlyphs {
        /// Label that could not be rendered.
        label: String,
    },
}

impl CaptchaError {
    fn invalid(field: &'static str, reason: &'static str) -> Self {
        Self::Invalid { field, reason }
    }
}

fn rng() -> Result<StdRng, CaptchaError> {
    Ok(StdRng::try_from_rng(&mut rand::rngs::OsRng)?)
}

/// The public images for one CAPTCHA challenge.
#[derive(Clone, Debug)]
pub struct Images {
    master: Image,
    prompt: Image,
}

impl Images {
    /// Returns the main image displayed to the user.
    #[must_use]
    pub fn master(&self) -> &Image {
        &self.master
    }

    /// Returns the click hint, puzzle piece, or rotating circular thumbnail.
    #[must_use]
    pub fn prompt(&self) -> &Image {
        &self.prompt
    }
}

/// A generated pair of images and the answer the application keeps server-side.
#[derive(Clone)]
#[must_use]
pub struct Challenge<A> {
    images: Images,
    answer: A,
}

impl<A> Challenge<A> {
    fn new(master: Image, prompt: Image, answer: A) -> Self {
        Self {
            images: Images { master, prompt },
            answer,
        }
    }

    /// Borrows the images to present to the client.
    #[must_use]
    pub fn images(&self) -> &Images {
        &self.images
    }

    /// Borrows the verification data for server-side storage or validation.
    #[must_use]
    pub fn answer(&self) -> &A {
        &self.answer
    }

    /// Separates the images and answer so an application can store them independently.
    #[must_use]
    pub fn into_parts(self) -> (Images, A) {
        (self.images, self.answer)
    }
}

impl<A> std::fmt::Debug for Challenge<A> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Challenge")
            .field("master", &self.images.master)
            .field("prompt", &self.images.prompt)
            .finish_non_exhaustive()
    }
}