caprs 0.1.1

Image-based click, slide, drag and rotate CAPTCHA generation and verification
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
//! Generate horizontal slide or free-drag puzzles from whole background images.

use std::ops::RangeInclusive;

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

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

const EDGE_MARGIN: u32 = 5;
const TEMPLATE_SIDE: u32 = 96;

/// How a puzzle piece is moved toward its target.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
pub enum Mode {
    /// The tile starts to the left at the same y coordinate as its target.
    #[default]
    Slide,
    /// The tile starts at a configured edge and can move along both axes.
    DragDrop,
}

/// The starting edge for a free-drag puzzle piece.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum Edge {
    /// Left side of the canvas.
    Left,
    /// Right side of the canvas.
    Right,
    /// Top side of the canvas.
    Top,
    /// Bottom side of the canvas.
    Bottom,
}

/// How decoy holes are arranged vertically.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
pub enum VerticalPlacement {
    /// All holes share a row.
    #[default]
    Aligned,
    /// Each hole is sampled independently along the y axis.
    Independent,
}

/// Alpha mask, hole graphic, and decorative overlay for a puzzle template.
///
/// All three layers are resized to the chosen tile size and rotated together. Use the
/// same canvas and alignment for each layer. The mask's alpha channel controls how
/// the source image is cut. An empty transparent overlay is useful for borderless pieces.
#[derive(Clone, Debug)]
pub struct Graph {
    mask: RgbaImage,
    shadow: RgbaImage,
    overlay: RgbaImage,
}

impl Graph {
    /// Sets the mask, hole shadow, and tile overlay in that order.
    #[must_use]
    pub fn new(mask: RgbaImage, shadow: RgbaImage, overlay: RgbaImage) -> Self {
        Self {
            mask,
            shadow,
            overlay,
        }
    }

    /// Generates a jigsaw template with one tab and one notch.
    #[must_use]
    pub fn puzzle() -> Self {
        // Use the same signed distance for every layer so the hole follows the tile's outline.
        let distance = |x: u32, y: u32| {
            let x = f64::from(x) + 0.5;
            let y = f64::from(y) + 0.5;
            let body = (x - 15.0).min(81.0 - x).min(y - 23.0).min(83.0 - y);
            let tab = 14.0 - (x - 48.0).hypot(y - 23.0);
            let notch = (x - 81.0).hypot(y - 53.0) - 13.0;
            body.max(tab).min(notch)
        };
        let coverage = |distance: f64| (distance + 0.5).clamp(0.0, 1.0);
        let mask = RgbaImage::from_fn(TEMPLATE_SIDE, TEMPLATE_SIDE, |x, y| {
            image::Rgba([
                255,
                255,
                255,
                (255.0 * coverage(distance(x, y))).round() as u8,
            ])
        });
        let shadow = RgbaImage::from_fn(TEMPLATE_SIDE, TEMPLATE_SIDE, |x, y| {
            image::Rgba([0, 0, 0, render::multiply_alpha(mask[(x, y)][3], 155)])
        });
        let overlay = RgbaImage::from_fn(TEMPLATE_SIDE, TEMPLATE_SIDE, |x, y| {
            let distance = distance(x, y);
            let outline = coverage(distance) - coverage(distance - 1.6);
            image::Rgba([255, 255, 255, (135.0 * outline).round() as u8])
        });
        Self::new(mask, shadow, overlay)
    }
}

/// Candidate full background images and puzzle templates.
#[derive(Clone, Debug)]
pub struct Resources {
    backgrounds: Vec<RgbaImage>,
    graphs: Vec<Graph>,
}

impl Resources {
    /// Sets the full background images and custom puzzle templates to sample.
    #[must_use]
    pub fn new(backgrounds: Vec<RgbaImage>, graphs: Vec<Graph>) -> Self {
        Self {
            backgrounds,
            graphs,
        }
    }

    /// Uses the built-in jigsaw template to cut pieces out of the supplied images.
    #[must_use]
    pub fn from_backgrounds(backgrounds: Vec<RgbaImage>) -> Self {
        Self::new(backgrounds, vec![Graph::puzzle()])
    }
}

/// Image, tile, and placement options shared by slider and free-drag puzzles.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct Options {
    /// Pixel dimensions of the main image.
    pub image_size: Size,
    /// Opacity multiplier for the composed image and tile.
    pub image_opacity: u8,
    /// Inclusive range of square tile sizes.
    pub tile_size: RangeInclusive<u32>,
    /// Inclusive ranges of clockwise template angles. Empty means unrotated.
    pub angles: Vec<RangeInclusive<i16>>,
    /// Total number of holes, including the target and any decoys.
    pub holes: u32,
    /// Candidate starting edges for free dragging.
    pub start_edges: Vec<Edge>,
    /// How hole rows are sampled in free-drag mode.
    pub vertical_placement: VerticalPlacement,
}

impl Default for Options {
    fn default() -> Self {
        Self {
            image_size: Size::new(300, 220),
            image_opacity: 255,
            tile_size: 60..=70,
            angles: Vec::new(),
            holes: 1,
            start_edges: vec![Edge::Left, Edge::Right, Edge::Top, Edge::Bottom],
            vertical_placement: VerticalPlacement::Aligned,
        }
    }
}

/// Verification data and client-facing starting position of a puzzle piece.
#[derive(Clone, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Answer {
    target: Rect,
    start: Point,
    angle: i16,
}

impl Answer {
    /// Returns the server-side destination rectangle in original image pixels.
    #[must_use]
    pub fn target(&self) -> Rect {
        self.target
    }

    /// Returns the top-left point where the client initially displays the tile.
    #[must_use]
    pub fn start(&self) -> Point {
        self.start
    }

    /// Returns the clockwise angle already applied to the tile and hole images.
    #[must_use]
    pub fn angle(&self) -> i16 {
        self.angle
    }

    /// Checks the submitted top-left point against the target on both axes.
    #[must_use]
    pub fn verify(&self, point: Point, padding: u32) -> bool {
        validate(point, self.target.origin, padding)
    }
}

/// Checks symmetric, inclusive padding on each axis around a target point.
#[must_use]
pub fn validate(point: Point, target: Point, padding: u32) -> bool {
    point.x.abs_diff(target.x) <= padding && point.y.abs_diff(target.y) <= padding
}

/// A reusable generator for slide and free-drag CAPTCHAs.
#[derive(Debug)]
pub struct Captcha {
    options: Options,
    mode: Mode,
    resources: Resources,
}

impl Captcha {
    /// Validates the selected layout and image resources.
    ///
    /// # Errors
    ///
    /// Returns an error if resources are missing or the largest tile cannot fit the layout.
    pub fn new(options: Options, mode: Mode, resources: Resources) -> Result<Self, CaptchaError> {
        validate_options(&options, mode)?;
        if resources.backgrounds.is_empty() || resources.graphs.is_empty() {
            return Err(CaptchaError::invalid(
                "slide resources",
                "need at least one background and one template",
            ));
        }
        for image in &resources.backgrounds {
            render::check_image(image, "slide background")?;
        }
        for graph in &resources.graphs {
            for (image, field) in [
                (&graph.mask, "tile mask"),
                (&graph.shadow, "tile shadow"),
                (&graph.overlay, "tile overlay"),
            ] {
                render::check_size(Size::new(image.width(), image.height()), field)?;
            }
            if !graph.mask.pixels().any(|pixel| pixel[3] != 0) {
                return Err(CaptchaError::invalid(
                    "tile mask",
                    "must contain visible pixels",
                ));
            }
        }
        Ok(Self {
            options,
            mode,
            resources,
        })
    }

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

    /// Draws the JPEG with holes and the corresponding transparent PNG piece.
    ///
    /// # 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 size = options.image_size;
        let side = rng.random_range(options.tile_size.clone());
        let turn = render::angle(&options.angles, &mut rng);
        let edge = match self.mode {
            Mode::Slide => Edge::Left,
            Mode::DragDrop => *choose_resource(&options.start_edges, &mut rng),
        };
        let layout = Layout::new(size, side, edge);
        let positions = layout.positions(options, self.mode, &mut rng);
        let target = *choose_resource(&positions, &mut rng);
        let start = layout.start(self.mode, target, &mut rng);

        let graph = choose_resource(&self.resources.graphs, &mut rng);
        let source = choose_resource(&self.resources.backgrounds, &mut rng);
        let mut master = render::crop_background(source, size, &mut rng);
        // Cut from the unmarked image before painting the real hole and decoys.
        let mut tile =
            imageops::crop_imm(&master, target.x as u32, target.y as u32, side, side).to_image();
        let prepare = |image: &RgbaImage| {
            let layer = render::scale(image.clone(), side, side);
            render::rotate(layer, turn, Size::square(side))
        };
        let mask = prepare(&graph.mask);
        for (pixel, mask_pixel) in tile.pixels_mut().zip(mask.pixels()) {
            pixel[3] = render::multiply_alpha(pixel[3], mask_pixel[3]);
        }
        imageops::overlay(&mut tile, &prepare(&graph.overlay), 0, 0);
        let shadow = prepare(&graph.shadow);
        for point in positions {
            imageops::overlay(&mut master, &shadow, i64::from(point.x), i64::from(point.y));
        }
        render::opacity(&mut master, options.image_opacity);
        render::opacity(&mut tile, options.image_opacity);
        Ok(Challenge::new(
            Image::new(master, Format::Jpeg),
            Image::new(tile, Format::Png),
            Answer {
                target: Rect::new(target, Size::square(side)),
                start,
                angle: turn,
            },
        ))
    }
}

fn choose_resource<'a, T>(resources: &'a [T], rng: &mut impl Rng) -> &'a T {
    resources
        .choose(rng)
        .expect("generator configuration guarantees nonempty candidates")
}

fn validate_options(options: &Options, mode: Mode) -> Result<(), CaptchaError> {
    let size = options.image_size;
    render::check_size(size, "image_size")?;
    render::check_range(
        &options.tile_size,
        1..=size.width.min(size.height),
        "tile_size",
    )?;
    render::check_angles(&options.angles, -360..=360)?;
    if options.holes == 0 {
        return Err(CaptchaError::invalid(
            "holes",
            "at least one hole is required",
        ));
    }
    let edges = match mode {
        Mode::Slide => &[Edge::Left][..],
        Mode::DragDrop if options.start_edges.is_empty() => {
            return Err(CaptchaError::invalid(
                "start_edges",
                "at least one edge is required",
            ));
        }
        Mode::DragDrop => &options.start_edges,
    };
    let side = *options.tile_size.end();
    if edges
        .iter()
        .any(|&edge| !Layout::new(size, side, edge).fits(options.holes))
    {
        return Err(CaptchaError::invalid(
            "slide layout",
            "largest tile, starting edge and holes must fit without overlap",
        ));
    }
    Ok(())
}

struct Layout {
    size: Size,
    side: u32,
    edge: Edge,
    x: RangeInclusive<u32>,
    y: RangeInclusive<u32>,
}

impl Layout {
    fn new(size: Size, side: u32, edge: Edge) -> Self {
        let strip = |at_edge| if at_edge { side } else { 0 };
        let left = EDGE_MARGIN + strip(edge == Edge::Left);
        let top = EDGE_MARGIN + strip(edge == Edge::Top);
        let right = size
            .width
            .saturating_sub(EDGE_MARGIN + strip(edge == Edge::Right));
        let bottom = size
            .height
            .saturating_sub(EDGE_MARGIN + strip(edge == Edge::Bottom));
        Self {
            size,
            side,
            edge,
            x: left..=right,
            y: top..=bottom,
        }
    }

    fn fits(&self, holes: u32) -> bool {
        self.x.end().saturating_sub(*self.x.start()) / holes >= self.side
            && self.y.end().saturating_sub(*self.y.start()) >= self.side
    }

    fn positions(&self, options: &Options, mode: Mode, rng: &mut impl Rng) -> Vec<Point> {
        // One horizontal slot per hole keeps the true hole and decoys from overlapping.
        let slot_width = (self.x.end() - self.x.start()) / options.holes;
        let y = *self.y.start()..=self.y.end() - self.side;
        let shared_y = rng.random_range(y.clone());
        (0..options.holes)
            .map(|index| {
                let left = self.x.start() + index * slot_width;
                let x = rng.random_range(left..=left + slot_width - self.side);
                let y = if mode == Mode::DragDrop
                    && options.vertical_placement == VerticalPlacement::Independent
                {
                    rng.random_range(y.clone())
                } else {
                    shared_y
                };
                Point::new(x as i32, y as i32)
            })
            .collect()
    }

    fn start(&self, mode: Mode, target: Point, rng: &mut impl Rng) -> Point {
        if mode == Mode::Slide {
            return Point::new(EDGE_MARGIN as i32, target.y);
        }
        let right = self.size.width - self.side - EDGE_MARGIN;
        let bottom = self.size.height - self.side - EDGE_MARGIN;
        let (x, y) = match self.edge {
            Edge::Left => (EDGE_MARGIN, rng.random_range(EDGE_MARGIN..=bottom)),
            Edge::Right => (right, rng.random_range(EDGE_MARGIN..=bottom)),
            Edge::Top => (rng.random_range(EDGE_MARGIN..=right), EDGE_MARGIN),
            Edge::Bottom => (rng.random_range(EDGE_MARGIN..=right), bottom),
        };
        Point::new(x as i32, y as i32)
    }
}