Skip to content
lib-xPublic

About

Rust library for image-based click, slide, drag and rotate CAPTCHAs

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

2 Commits

Folders and files

Repository files navigation

caprs

crates.io version

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 from crates.io

Use Rust 1.88 or later. Run this command from the directory containing your project's Cargo.toml.

cargo add caprs

To add the dependency by hand, put this in Cargo.toml.

[dependencies]
caprs = "0.1"

Use cargo add caprs --features serde to enable serialization of answers and coordinates for server-side storage. Crate on crates.io · API reference

Generate your first CAPTCHA

In a Cargo binary project with caprs installed, put this in src/main.rs.

use caprs::click;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let symbols = click::Symbols::bundled_text()?;
    let captcha = click::Captcha::new(click::Options::default(), symbols)?;
    let (images, answer) = captcha.generate()?.into_parts();

    images.master().save("captcha.jpg")?;
    images.prompt().save("hint.png")?;
    println!("The hint shows {} symbols to click.", answer.targets().len());
    Ok(())
}

Run cargo run to create captcha.jpg and hint.png in the working directory. The example uses the bundled font and a solid background. In a web application, send the images to the browser and keep answer on the server. Once the browser submits its ordered caprs::Point values in original image pixels, call answer.verify(&points, 5) with a five-pixel padding value.

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 from the repository

git clone https://github.com/lib-x/caprs.git
cd caprs
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.

About

Rust library for image-based click, slide, drag and rotate CAPTCHAs

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages