Skip to main content

caprs/
lib.rs

1//! Generate image-based CAPTCHA challenges and verify responses.
2//!
3//! Click CAPTCHAs use text or shapes. Slide and drag CAPTCHAs cut a piece from a
4//! background, and rotate CAPTCHAs ask the user to realign a circular crop.
5//! Keep the answer on the server and send the client only the images and any
6//! display metadata it needs. Use the original image coordinates for verification.
7//!
8//! ```
9//! use caprs::click;
10//!
11//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
12//! let captcha = click::Captcha::new(click::Options::default(), click::Symbols::bundled_text()?)?;
13//! let (images, answer) = captcha.generate()?.into_parts();
14//! let hint = images.prompt().to_data_url()?;
15//! assert!(hint.starts_with("data:image/png;base64,"));
16//! assert!(!answer.verify(&[], 0));
17//! # Ok(())
18//! # }
19//! ```
20
21pub mod click;
22mod output;
23mod render;
24pub mod rotate;
25pub mod slide;
26
27pub use image;
28pub use output::{Format, Image, ImageError};
29
30use rand::SeedableRng;
31use rand::rngs::StdRng;
32use thiserror::Error;
33
34/// A point in image pixels, measured from the top left with y increasing down.
35#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
36#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
37pub struct Point {
38    /// Horizontal coordinate.
39    pub x: i32,
40    /// Vertical coordinate.
41    pub y: i32,
42}
43
44impl Point {
45    /// Creates a point from its horizontal and vertical coordinates.
46    #[must_use]
47    pub const fn new(x: i32, y: i32) -> Self {
48        Self { x, y }
49    }
50}
51
52/// The width and height of an image or region in pixels.
53#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
54#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
55pub struct Size {
56    /// Horizontal extent in pixels.
57    pub width: u32,
58    /// Vertical extent in pixels.
59    pub height: u32,
60}
61
62impl Size {
63    /// Creates a size from its width and height.
64    #[must_use]
65    pub const fn new(width: u32, height: u32) -> Self {
66        Self { width, height }
67    }
68
69    /// Creates a size with equal width and height.
70    #[must_use]
71    pub const fn square(side: u32) -> Self {
72        Self::new(side, side)
73    }
74}
75
76/// A rectangle described by an image-space corner and pixel dimensions.
77#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
78#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
79pub struct Rect {
80    /// The upper-left point.
81    pub origin: Point,
82    /// Horizontal and vertical extent.
83    pub size: Size,
84}
85
86impl Rect {
87    /// Creates a rectangle from its upper-left corner and dimensions.
88    #[must_use]
89    pub const fn new(origin: Point, size: Size) -> Self {
90        Self { origin, size }
91    }
92}
93
94/// An invalid CAPTCHA configuration or a failure to generate a challenge.
95#[derive(Debug, Error)]
96#[non_exhaustive]
97pub enum CaptchaError {
98    /// A setting or resource is incompatible with the generator.
99    #[error("invalid {field}: {reason}")]
100    Invalid {
101        /// The name of the setting or resource.
102        field: &'static str,
103        /// The constraint that the value failed.
104        reason: &'static str,
105    },
106    /// The operating system could not provide randomness.
107    #[error("could not seed the challenge generator")]
108    Random(#[from] rand::rand_core::OsError),
109    /// A font mapped a label to glyphs without a renderable outline.
110    #[error("no visible glyphs for click label {label:?}")]
111    EmptyGlyphs {
112        /// Label that could not be rendered.
113        label: String,
114    },
115}
116
117impl CaptchaError {
118    fn invalid(field: &'static str, reason: &'static str) -> Self {
119        Self::Invalid { field, reason }
120    }
121}
122
123fn rng() -> Result<StdRng, CaptchaError> {
124    Ok(StdRng::try_from_rng(&mut rand::rngs::OsRng)?)
125}
126
127/// The public images for one CAPTCHA challenge.
128#[derive(Clone, Debug)]
129pub struct Images {
130    master: Image,
131    prompt: Image,
132}
133
134impl Images {
135    /// Returns the main image displayed to the user.
136    #[must_use]
137    pub fn master(&self) -> &Image {
138        &self.master
139    }
140
141    /// Returns the click hint, puzzle piece, or rotating circular thumbnail.
142    #[must_use]
143    pub fn prompt(&self) -> &Image {
144        &self.prompt
145    }
146}
147
148/// A generated pair of images and the answer the application keeps server-side.
149#[derive(Clone)]
150#[must_use]
151pub struct Challenge<A> {
152    images: Images,
153    answer: A,
154}
155
156impl<A> Challenge<A> {
157    fn new(master: Image, prompt: Image, answer: A) -> Self {
158        Self {
159            images: Images { master, prompt },
160            answer,
161        }
162    }
163
164    /// Borrows the images to present to the client.
165    #[must_use]
166    pub fn images(&self) -> &Images {
167        &self.images
168    }
169
170    /// Borrows the verification data for server-side storage or validation.
171    #[must_use]
172    pub fn answer(&self) -> &A {
173        &self.answer
174    }
175
176    /// Separates the images and answer so an application can store them independently.
177    #[must_use]
178    pub fn into_parts(self) -> (Images, A) {
179        (self.images, self.answer)
180    }
181}
182
183impl<A> std::fmt::Debug for Challenge<A> {
184    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
185        f.debug_struct("Challenge")
186            .field("master", &self.images.master)
187            .field("prompt", &self.images.prompt)
188            .finish_non_exhaustive()
189    }
190}