caprs 0.1.0

Image-based click, slide, drag and rotate CAPTCHA generation and verification
Documentation

caprs

A Rust library for image-based CAPTCHAs. Generate a challenge, send the images to the client, and check the response against the answer on the server.

Mode Client interaction Library output
Text click Click the letters, characters, or short labels shown in the hint, in order JPEG main image and PNG hint
Shape click Click the shapes shown in the hint, in order JPEG main image and PNG hint
Slide Move a piece horizontally into its matching hole JPEG main image and transparent PNG tile
Drag and drop Move a piece along both axes into its matching hole JPEG main image and transparent PNG tile
Rotate Rotate the inner crop to match the reference Two circular PNG images

Install

cargo add caprs

The minimum supported Rust version is 1.88. Enable the serde feature to serialize answers and coordinates for server-side storage.

Cut a puzzle tile from a whole image

Pass an ordinary PNG or JPEG to the slide generator. It crops the background, cuts the matching tile from it and paints the hole using the built-in puzzle template.

use caprs::{Point, image, slide};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let background = image::open("background.jpg")?.into_rgba8();
    let resources = slide::Resources::from_backgrounds(vec![background]);
    let captcha = slide::Captcha::new(slide::Options::default(), slide::Mode::Slide, resources)?;
    let (images, answer) = captcha.generate()?.into_parts();

    images.master().save("board.jpg")?;
    images.prompt().save("tile.png")?;
    let start = answer.start();
    println!("Display the tile initially at ({}, {})", start.x, start.y);

    // Use the submitted top-left position of the tile in original image pixels.
    let submitted = Point::new(165, 84);
    let passed = answer.verify(submitted, 5);
    println!("Verified: {passed}");
    Ok(())
}

Use slide::Mode::DragDrop for free movement and slide::Resources::new to supply custom mask, shadow and overlay images. The mask's alpha channel defines the cutout. Rotation similarly accepts whole images and creates the circular reference and smaller center crop. For graphic click puzzles, load individual transparent shapes or extract sprites from a larger image with click::Shape::from_region.

Customize text and backgrounds

use caprs::{Size, click, image};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let font = click::Font::from_bytes(std::fs::read("my-font.ttf")?)?;
    let symbols = click::Symbols::Text {
        labels: ["A", "C", "K", "M", "P", "X", "3", "7"]
            .map(str::to_owned)
            .to_vec(),
        fonts: vec![font],
    };

    let mut options = click::Options::default();
    options.image_size = Size::new(320, 220);
    options.prompt = click::Prompt::Subset(3..=3);
    let background = image::open("background.jpg")?.into_rgba8();
    let captcha = click::Captcha::new(options, symbols)?
        .with_backgrounds(click::Backgrounds::new(vec![background], vec![]))?;
    let challenge = captcha.generate()?;
    challenge.images().master().save("click.jpg")?;
    challenge.images().prompt().save("hint.png")?;
    Ok(())
}

Use click::Symbols::bundled_text()? for the default Chinese labels with the included open-source font. click::Font::bundled()? can also be combined with custom labels in the subset. Click options include symbol counts, size and angle ranges, palettes, shadows, opacity, hint noise, and separate hint backgrounds. Generated images can also be exported as bytes, Base64 or data URLs.

For verification, convert browser coordinates into original image pixels. Submit click points in hint order and the top-left tile position for slide or drag. For rotation, send the clockwise adjustment in degrees. A 90° generated rotation takes a 270° adjustment. Keep the answer on the server, associate it with a challenge ID, and enforce expiry and attempt limits in the application.

Run the example

cargo run --example generate
cargo run --example generate -- ./out ./background.jpg ./my-font.ttf

The example saves a main image and a prompt for every mode. With no arguments it uses a generated background and the bundled font, writing to target/caprs-example.

Credits and licenses

Thanks to Awen and the go-captcha contributors for the original library and CAPTCHA designs. Porting notes map the Go APIs to Rust and describe the compatibility decisions.